#!/usr/bin/perl -w use strict; $SIG{CHLD}=\&catchChildDeath; # Track how many children we have running our $children=0; # Limits on min and max for number of children to run my $min_child=5; my $max_child=10; # Enable or disable our ability to spawn my $spawnEnabled=1; # Run until killed while(1){ spawn(); sleep 5; } exit(0); # Deal with the death of a child. A sad event to be sure. sub catchChildDeath{ printf "Death of child noted.\n"; $children--; $children = ( $children < 0 ? 0 : $children); unless ($spawnEnabled){ $spawnEnabled = ( $children < $min_child ? 1 : 0 ); } printf "There are %d children running\n",$children; } # Spawn if we must, or not. sub spawn{ unless ( $spawnEnabled ) { if ($children <= $min_child ){ $spawnEnabled=1; } else { return unless $spawnEnabled; } } if ( fork()){ $children++; $spawnEnabled = 0 if $children > $max_child; printf "%d children running\n",$children; } else { kidPlay(); } } # This encapsulates the behavior of the child. sub kidPlay{ my $iter=0; printf "Child PID: %d\n",$$; while($iter++ < 10){ sleep 1; } printf "Child PID: %d exiting..",$$; exit(0); }