How to Fork in Perl

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);
}
This entry was posted in Forking, Perl and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>