我使用pipe(),fork(),dup(),execve()生成子进程.
从父级,是否可以安全地等待子级的stdin和stdout关闭(即read()返回0),然后执行waitpid()来收集终止状态?
或者,如果没有关闭stdin和stdout,进程会失败吗?(因此我的程序永远不会得到waitpid)
为了澄清,我问以下是否安全:
while (child_stdin != -1 && child_stdout != -1) {
poll(...)
if (got_stdout) {
n = read(child_stdout);
if (n >= 0) {
// do something with output
} else if (n == 0) {
child_stdout = -1
}
}
// same for stdin
}
waitpid(child_pid)
Run Code Online (Sandbox Code Playgroud)
或者可能会发生孩子终止,但我永远不会在read()或write()上得到0.
没有信号,只有poll() - ing.
如果进程a生成进程b,并且进程b生成进程c(c也就是孙子进程a),b可以终止并关闭它的stdout文件描述符的副本(可能是b'sstdout是a正在观看的管道的写入端.)但是c仍然有管道打开,所以a将获得SIGCHLD b,但不会在管道上获得EOF.换句话说,是的,可能会发生孩子终止但父母看不到管道关闭的情况.
此外,常见的编码错误a仍然是管道的写入侧打开.在这种情况下,b可以终止和关闭管道写入侧的副本,但父级永远不会看到管道关闭,因为父级正在保持打开状态.