http://www.perlmonks.org?node_id=237087

I needed a script that launched three instancies of the nmap network scanner to scan all our network in parallel. Each time a subnet is scanned and nmap finishes, another instance gets started to scan another subnet. This way I always have three parallel processes that do the job.

To learn how to do it I created this small script that could be a starting point for accomplishing similar tasks. You can substitute the sleep with an exec that runs an external program, for example, or fill that space with any perl you like!

Update: Thanks to other monks' suggestions I added "sanity checks": now the return value from fork and wait is checked. Thanks also to larsen, valdez, abell and alloalex's for their suggestions

#!/usr/bin/perl # forktest.pl # # I needed a script that launched three instancies of the nmap # network scanner to scan all our network in parallel. Each time # a subnet is scanned and nmap finishes, another instance gets # started to scan another subnet. This way I always have three # parallel processes that do the job. # # To learn how to do it I created this small script that could # be a starting point for accomplishing similar tasks. use strict ; use warnings ; my %childpid ; my $maxchild = 3 ; my $subnet = 1 ; do { while (keys(%childpid) < $maxchild and $subnet <= 254) { my $pid = fork ; # The following instruction comes from node 237098 die "Cannot fork: $!" unless defined $pid ; if ($pid) { # Parent process print "Child $pid started to scan subnet $subnet\n" ; $childpid{$pid} = $subnet++ ; } else { # Child process sleep rand 5 ; exit ; } } my $dead = wait ; # This die added after merlyn's suggestion # If you want to check a waitpid solution, see the code # posted by merlyn and zentara die "Something weird happened while wait!" if $dead == -1 ; print "Subnet $childpid{$dead} scan completed by child $dead\n" ; delete $childpid{$dead} ; } while (keys(%childpid) > 0) ;