我有这个代码
# 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;
}
可以运行一个或多个命令。
如果给定命令之一失败,我会尝试使其停止。
实际上,即使一个命令失败,它也会继续运行
./test 'ech foo' 'echo too'
sh: 1: ech: not found
too
我确实使用 wait()
和 waitpid()
尝试了多种解决方案,但仍然不起作用。
最佳答案
当 shell 无法执行程序时,子进程的退出状态将为非零。您可以通过评估从 wait()
调用返回的 status
变量来进行检查。
这并不是那么简单,因为 wait()
将更多信息打包到 status
中,而不仅仅是退出代码。此外,可用信息还会根据 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;
}
关于c - 通过 fork()/execl() 确定进程运行的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37597852/