#! /usr/bin/perl -w use strict ; my $OUT = 'out' ; my $prog = substr($0,rindex($0,'/')+1) ; my $Usage = <', $OUT or Error "can't write $OUT ($!)" ; close $fh ; # open the log for all to append to open $fh, '>>', $OUT or Error "can't append $OUT ($!)" ; sub count { my $hash = shift ; scalar keys %$hash ; } sub child { my $num = shift ; my $rand = int ( rand 10 ) ; my $msg = sprintf "... job %3d : sleep %2d ; %s\n" , $num, $rand, $$ ; print $msg ; sleep $rand ; # want msgs appended to file, so don't use buffered io syswrite $fh, $msg ; close $fh ; exit ; } while ( @QUE or count $jobs ) { if ( @QUE and count ( $jobs ) < $PAR ) { # some work to fork my $num = shift @QUE ; my $pid = fork ; Error "can't fork" unless defined $pid ; if ( $pid ) { # parent $jobs -> { $pid } = $num ; printf "started job %3d ; active %2d\n", $num , count $jobs ; } else { # child ; the work goes here child $num ; } } else { my $pid = wait ; my $num = delete $jobs -> { $pid } ; printf "ended job %3d ; active %2d\n", $num, count $jobs ; } } close $fh ;