Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 17th, 2012  |  syntax: None  |  size: 0.86 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #!/usr/bin/perl
  2.  
  3. # Demonstrate handling of waiting for the exit values from multiple
  4. # forked child processes.  Code based on that in the perlipc man page.
  5.  
  6. use strict;
  7. use warnings;
  8. use feature "say";
  9. use POSIX ":sys_wait_h"; # for waitpid
  10.  
  11. my $num_procs = 3;
  12. #my $cmd = '/usr/bin/true';
  13. my $cmd = '/usr/bin/false';
  14. my %children;
  15.  
  16. $SIG{CHLD} = sub {
  17.         local($!, $?);
  18.         my $pid = waitpid(-1, WNOHANG);
  19.         return if $pid == -1;
  20.         return unless defined $children{$pid};
  21.         delete $children{$pid};
  22.         cleanup_child($pid, $?);
  23. };
  24.  
  25. for (1..$num_procs) {
  26.         my $pid = fork();
  27.         # parent
  28.         if ($pid) {
  29.                 say "forked $pid";
  30.                 $children{$pid} = 1;
  31.         }
  32.         # child
  33.         else {
  34.                 exec $cmd;
  35.         }
  36. }
  37.  
  38. while (keys %children) {
  39.         my @pids = keys %children;
  40.         my $pids = join ', ', @pids;
  41.         say "waiting for kids: $pids";
  42.         sleep 2;
  43. }
  44.  
  45. exit;
  46.  
  47. sub cleanup_child {
  48.         my($pid, $val) = @_;
  49.         say "child $pid had val $val";
  50. }
  51.  
  52. __END__