#!/usr/bin/perl -w use strict; use Unix::PID; ## problem code: my $pid = Unix::PID->new(); #my @pids = $pid->get_pidof('fork.pl'); #die "one copy of me is already running\n" if scalar(@pids) > 0; ## :problem code print ": my process id: $$\n"; my $childcnt = 0; foreach my $process (@ARGV) { my $pid = fork; if (defined $pid ) { if ($pid ) { # parent process if (++$childcnt >= 2) { # hit child limit print ": must wait to start more\n"; my $completed_pid = wait; $childcnt--; print ": $completed_pid is done; $childcnt running\n"; } else { # more children ok print ": $childcnt running; can start more\n"; } } else { # child process print "<$process>: my id: $$\n"; sleep int(rand(10)); print "<$process>: end: $$\n"; exit 0; } } else { # fork failed warn ": fork failed $!\n"; last; } } print ": waiting for $childcnt to complete\n"; until ((my $completed_pid = wait) == -1) { $childcnt--; print ": $completed_pid is done; $childcnt running\n"; }; print ": complete; $childcnt process(es) left\n";