Skip to content

Instantly share code, notes, and snippets.

@jzawodn
Created March 26, 2012 18:31
Show Gist options
  • Save jzawodn/2208527 to your computer and use it in GitHub Desktop.
Save jzawodn/2208527 to your computer and use it in GitHub Desktop.
#!/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