Created
March 26, 2012 18:31
-
-
Save jzawodn/2208527 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
# Demonstrate handling of waiting for the exit values from multiple | |
# forked child processes. Code based on that in the perlipc man page. | |
use strict; | |
use warnings; | |
use feature "say"; | |
use POSIX ":sys_wait_h"; # for waitpid | |
my $num_procs = 3; | |
#my $cmd = '/usr/bin/true'; | |
my $cmd = '/usr/bin/false'; | |
my %children; | |
$SIG{CHLD} = sub { | |
local($!, $?); | |
my $pid = waitpid(-1, WNOHANG); | |
return if $pid == -1; | |
return unless defined $children{$pid}; | |
delete $children{$pid}; | |
cleanup_child($pid, $?); | |
}; | |
for (1..$num_procs) { | |
my $pid = fork(); | |
# parent | |
if ($pid) { | |
say "forked $pid"; | |
$children{$pid} = 1; | |
} | |
# child | |
else { | |
exec $cmd; | |
} | |
} | |
while (keys %children) { | |
my @pids = keys %children; | |
my $pids = join ', ', @pids; | |
say "waiting for kids: $pids"; | |
sleep 2; | |
} | |
exit; | |
sub cleanup_child { | |
my($pid, $val) = @_; | |
say "child $pid had val $val"; | |
} | |
__END__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment