Wait multiple process, print exit code if any process get exit
You can use wait -n
to wait for a child to exit, then test each child to if they are still running with kill -0
, to see which one just exited, like this:
for f in 15 10 15; do sleep $f & PIDS+="$! " ; done ; wait -n ; for f in $PIDS; do if ! kill -0 $f 2> /dev/null ; then echo $f; fi;
wait -n
only returns the exit status of the child, not which PID
it was.
I thought about Bash's wait -n
, but it doesn't let you know which child process exited. How about a simple Perl script?
#!/usr/bin/perl
use strict;
use warnings;
use POSIX ":sys_wait_h";
sub spawn(@) {
my $pid = fork();
die "fork: $!" if not defined $pid;
if ($pid == 0) {
exec @_ or die "exec: $!";
}
return $pid;
}
# Commands to run
my $p1 = spawn '/bin/bash -c "sleep 6; kill $$"';
my $p2 = spawn '/bin/bash -c "sleep 4; exit 4"';
print "spawned PIDs $p1 and $p2\n";
while ((my $child = waitpid(-1, 0)) > 0) {
my $code = $? >> 8;
my $status = $? & 0xff;
printf "child %d finished with exit code %d (status/sig %d)\n", $child, $code, $status;
}