I don't think waitpid(-1, &cstatus, WNOHANG);
does what you think it does. You need to check its return value. If it is > 0
, that's the PID of the child process that has exited. If it's 0
or -1
, no child process has changed state.
You can just call waitpid(-1, &cstatus, WNOHANG);
before and/or after each command you run. Call it in a loop to catch more than one child exit.
You can also handle SIGCHILD. Your process will receive this signal immediately after a child exit, which is good if you want to report child process termination immediately, without waiting for user's input.