Skip to content

Instantly share code, notes, and snippets.

@khan5v
Last active November 3, 2016 13:27
Show Gist options
  • Save khan5v/61314a872c4931173858d69bbea847ff to your computer and use it in GitHub Desktop.
Save khan5v/61314a872c4931173858d69bbea847ff to your computer and use it in GitHub Desktop.
Perl fork() example with multiple child processes involved
use strict;
use warnings;
my $spawn_processes = 5;
my $forked = 0;
my $err = 0;
print "($$) parent has started\n";
foreach(1..$spawn_processes) {
my $child_pid = fork();
if(defined $child_pid && $child_pid > 0) {
## Parent
$forked++;
} elsif(defined $child_pid){
## Child
print "($$) has started\n";
for(1..100000000) {
my $x = $_ + 123;
}
## Never forget to exit since the finalization part
## should only be executed by the parent process
exit;
} else {
## unable to fork
$err++;
}
}
## Only parent gets here
## Waiting for all the successful child processes to finish
for(1..$forked) {
my $pid = wait();
print "($$) $pid has finished\n";
}
print "$$ parent process has finished with:\n";
print " -> $forked child processes finishing just fine\n";
print " -> $err child processes breaking\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment