Reputation: 3884
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?
Upvotes: 3
Views: 551
Reputation: 3153
You can trap SIGCHLD, something like this:
$SIG{CHLD} = sub {
my $child;
while ( ( $child = waitpid( -1, WNOHANG ) ) > 0 ) {
warn("Reaped $child, exited with $?");
}
};
Upvotes: 2
Reputation: 13792
You can use the wait function, it waits for a child process to terminate and returns the pid of the deceased process.
Upvotes: 3