Archive

Posts Tagged ‘Forking’

How to Fork in Perl

March 26th, 2008 Masao No comments

Kick off multiple processes simultaneously in Perl.

my $num = 10;

my @children;

for (my $i = 0; $i < $num; $i++) {
  my $pid = fork();
  if ($pid) { # parent
    push @children, $pid;
  } elsif ($pid == 0) { # child
    print "child $i\n";
    sleep 5;
    exit;
  } else {
    print STDERR "couldn't fork\n";
  }
}

foreach my $child (@children) {
  waitpid($child, 0);
}
Categories: Forking, Perl Tags: