[英]Determine the outcome of process ran via fork()/execl()
我有这个代码
# 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
,...的值而WIFCONTINUED
。
如果我们对孩子已通过正常路径成功退出这一事实感兴趣,则可以使用:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.