#!/usr/bin/perl -w use strict; ############################################################################ ## Load the neccesary modules ############################################################################ use POSIX 'setsid'; use strict; use POSIX ":sys_wait_h"; ################################################################# # Global variables used in the script # ################################################################# my $SLEEP_TIME=120; my $pid = 0; my $counter = 0; my $MAX_PROCESS = 75; my $STOP_FILE = 'stopfile'; my $num_processes = 0; my $process_name = $0; ################################################################ # Handle any zombies # ################################################################ $SIG{CHLD} = \&REAPER; sub REAPER { my $stiff; while (($stiff = waitpid(-1, &WNOHANG)) > 0) { # do something with $stiff if you want } $SIG{CHLD} = \&REAPER; # install *after* calling waitpid } ############################################################### # This subroutine stops the processes gracefully allowing the # # processes that are running to complete and then it shuts # # down the script. # ############################################################### sub stopGraceful() { while(-e $STOP_FILE && ($num_processes > 1)) { $num_processes = `ps -ef | grep $process_name | grep -v grep | wc -l`; chomp($num_processes); print "Process number $num_processes.\n"; if($num_processes == 1) { exit(0); } } } sub mainLoop() { while(!(-e $STOP_FILE)) { $counter++; $num_processes = `ps -ef | grep $process_name | grep -v grep | wc -l`; chomp($num_processes); if($num_processes <= $MAX_PROCESS) { $pid = fork(); die "Cannot fork: $!" unless defined($pid); if ($pid == 0) { # Child process # Insert database_worker script here. print $counter . " : Process number $num_processes.\n"; sleep(int(rand($SLEEP_TIME))); exit(0); # Child process exits when it is done. } # else 'tis the parent process } } if (-e $STOP_FILE) { stopGraceful(); exit(0); } } ############################# ## ## ## ## ## Execution Begins Here ## ## Begin Main Loop ## ## ## ## ## ############################# mainLoop(); #### $num_processes = `ps -ef | grep $process_name | grep -v grep | wc -l`;