Standard approach to determine success or failure of fork/exec (while parent is running simultaneously)? Standard approach to determine success or failure of fork/exec (while parent is running simultaneously)? unix unix

Standard approach to determine success or failure of fork/exec (while parent is running simultaneously)?


Your parent process can use the pid of the child process to detect that it is alive or has exited (and can disambiguate the error code, and died-because-of-signal errors, see waitpid). You can use certain error codes or signals to notify the parent about specific error cases (e.g., in the forked child before the exec), but for a completely generic child, you may not be able to reserve any exit codes or signals (since the parent won't be able to tell if the exec succeeded and then the child exited with those values).

Another approach often used is to create a pipe fd pair (see the 'pipe' syscall), and pass one end to the child (generally the write end) and the other to the parent. The child can use this to send specific error codes to the parent. And the parent can detect premature termination if the pipe is closed without getting any data. There are some pitfalls: SIGPIPE will be sent to the parent if it reads on a pipe with no active writers, and using up an fd (other than stdin/stdout/stderr) in a child process may confuse some badly-written child processes (though close-on-exec can help fix that).

In general, all the code I've seen to make fork+exec robust is pretty hacky.