Posts Tagged ‘Forking’

How to Fork in Perl

Wednesday, March 26th, 2008

Kick off multiple processes simulataneously 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);
}