I spawn a child process using pipe(), fork(), dup(), execve().
From the parent, is it safe to wait for stdin and stdout of the child to close (i.e. read() return 0 on both), and then do waitpid() to collect the termination status?
Or can it happen that the process will fail without ever closing stdin and stdout? (thus my program never getting to waitpid)
To clarify, I’m asking whether the following is safe:
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)
Or can it happen that child will terminate, but I’ll never get 0 on read() or write().
No signals are involved, just poll()-ing.
If process
aspawns processb, and processbspawns processc(socis the grandchild ofa),bcan terminate and close its copy of the file descriptor that was its stdout (presumably,b'sstdout is the write side of a pipe thatais watching.) Butcstill has that pipe open, soawill get the SIGCHLD fromb, but will not get EOF on the pipe. In other words, yes, it can happen that the child terminates but the parent does not see the pipe close.Also, it is a common coding error that
astill has the write side of the pipe open. In that case,bcan terminate and close its copy of the write side of the pipe, but the parent never sees the pipe close because the parent is keeping it open.