sub afork (@$&) { # First field = array, second field = max number of processes to # run at the same time, third field = subroutine to run against # each array element my ($data, $max, $code) = @_; my $c = 0; foreach my $data (@$data) { wait unless ++ $c <= $max; die "Fork failed: $!\n" unless defined (my $pid = fork); exit $code -> ($data) unless $pid; } 1 until -1 == wait; } while(1) { @FILES = `ls -1 $DIRECTORY`; afork (\@FILES,3,\&process_file); }