+-

我做常规的事情:
> fork()
> execvp(cmd,)在孩子身上
如果execvp因为没有找到cmd而失败,我怎么能在父进程中注意到这个错误?
最佳答案
为此目的,着名的 self-pipe trick可以是 adapted.
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
#include <sysexits.h>
#include <unistd.h>
int main(int argc, char **argv) {
int pipefds[2];
int count, err;
pid_t child;
if (pipe(pipefds)) {
perror("pipe");
return EX_OSERR;
}
if (fcntl(pipefds[1], F_SETFD, fcntl(pipefds[1], F_GETFD) | FD_CLOEXEC)) {
perror("fcntl");
return EX_OSERR;
}
switch (child = fork()) {
case -1:
perror("fork");
return EX_OSERR;
case 0:
close(pipefds[0]);
execvp(argv[1], argv + 1);
write(pipefds[1], &errno, sizeof(int));
_exit(0);
default:
close(pipefds[1]);
while ((count = read(pipefds[0], &err, sizeof(errno))) == -1)
if (errno != EAGAIN && errno != EINTR) break;
if (count) {
fprintf(stderr, "child's execvp: %s\n", strerror(err));
return EX_UNAVAILABLE;
}
close(pipefds[0]);
puts("waiting for child...");
while (waitpid(child, &err, 0) == -1)
if (errno != EINTR) {
perror("waitpid");
return EX_SOFTWARE;
}
if (WIFEXITED(err))
printf("child exited with %d\n", WEXITSTATUS(err));
else if (WIFSIGNALED(err))
printf("child killed by %d\n", WTERMSIG(err));
}
return err;
}
这是一个完整的计划.
$./a.out foo child's execvp: No such file or directory $(sleep 1 && killall -QUIT sleep &); ./a.out sleep 60 waiting for child... child killed by 3 $./a.out true waiting for child... child exited with 0
这是如何工作的:
创建管道,并使写入端点CLOEXEC:成功执行exec时自动关闭.
在孩子,尝试执行.如果成功,我们将无法控制,但管道已关闭.如果失败,请将失败代码写入管道并退出.
在父级中,尝试从其他管道端点读取.如果read返回零,则管道关闭,子节点必须成功执行exec.如果read返回数据,那就是我们孩子写的失败代码.
点击查看更多相关文章
转载注明原文:c – fork()之后如何处理execvp(…)错误? - 乐贴网