antred antred - 23 days ago 7
Perl Question

(fork / waitpid) Wait for a list of child processes but interrupt the wait every time a child finishes

I'm using

fork
to spawn a number of child processes that run several tasks in parallel. In my case it is not sufficient to simply wait on all child processes in a loop, because if the first process in my list is the last to finish then my
waitpid
call would block until that process has finished.

I want my
waitpid
call to wake up every time a process has finished. The reason is that I immediately want to inspect the finished child process's exit code to determine if the process was successful so I can cancel any child processes still running. In my case, there is no point in letting them continue (potentially for hours!) if any child process returns a non-zero exit code because that would indicate an error, and even a single error would make the whole undertaking pointless.

(EDIT: I know that that's not how
waitpid
actually works, but I'm looking for something like that.)

Now, I could do this by using a loop to call
waitpid
with the
WNOHANG
flag and then keep checking my child processes with sleep intervals between individual
waitpid
calls, but this solution seems like a hack. Does anyone have a more elegant solution?

Answer

You can use the wait function, it waits for a child process to terminate and returns the pid of the deceased process.

Comments