Last active
November 3, 2016 13:27
-
-
Save khan5v/61314a872c4931173858d69bbea847ff to your computer and use it in GitHub Desktop.
Perl fork() example with multiple child processes involved
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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