确定通过fork()/execl()运行的进程的结果
我有这个密码确定通过fork()/execl()运行的进程的结果,c,bash,fork,C,Bash,Fork,我有这个密码 # include <stdio.h> # include <unistd.h> # include <sys/wait.h> # include <stdlib.h> # include <string.h> # include <assert.h> int parse( char * arg) { int t; t = fork(); if (t < 0)
# include <stdio.h>
# include <unistd.h>
# include <sys/wait.h>
# include <stdlib.h>
# include <string.h>
# include <assert.h>
int parse( char * arg)
{
int t;
t = fork();
if (t < 0)
return -1;
if (t == 0)
{
execl("/bin/sh", "sh", "-c", arg,NULL);
exit(1);
}
return t;
}
int main(int argc, char *argv[])
{
int t, tt, status, i;
i = 1;
for (i=1; i < argc; i++)
{
t = parse(argv[i]);
tt = wait(&status);
assert(tt == t);
}
return 0;
}
我尝试了多个wait和waitpid解决方案,但仍然不起作用。当shell无法执行程序时,子进程的退出状态将为非零。您可以通过评估wait调用返回的状态变量进行检查 这并不是那么简单,因为等待将更多信息打包到状态中,而不仅仅是退出代码。此外,可用信息也会根据WIFCONTINUED、WIFEXITED等的值而变化 如果我们对孩子通过正常路径成功退出感兴趣,我们可以使用:
int
main(int argc, char *argv[])
{
int t, tt, status, i;
i = 1;
for (i=1; i < argc; i++)
{
t = parse(argv[i]);
tt = wait(&status);
assert(tt == t);
if ((! WIFEXITED(status)) || (WEXITSTATUS(status) != 0)) {
fprintf(stderr, "Command '%s' failed, aborting...", argv[i]));
return 1;
}
}
return 0;
}
可能会有所帮助您可以用一个简单的shell脚本来实现这一点:try{for cmd do eval$cmd | | return;done;}test是一个标准的shell命令,因此将其用于其他目的是不明智的。
int
main(int argc, char *argv[])
{
int t, tt, status, i;
i = 1;
for (i=1; i < argc; i++)
{
t = parse(argv[i]);
tt = wait(&status);
assert(tt == t);
if ((! WIFEXITED(status)) || (WEXITSTATUS(status) != 0)) {
fprintf(stderr, "Command '%s' failed, aborting...", argv[i]));
return 1;
}
}
return 0;
}