#!/usr/bin/perl use strict; use warnings; print "Begin Main\n"; ## we store the child process in this array my @childArray; ## path to the files go in this array. It could be one or a dozen ## and is determined by another process our @fileArray = qw(fileone.txt filetwo.txt filethree.txt); ## This is the number of forks we will allow my $forkCeiling = "5"; my $pid; my $fileName; for ( my $forkCount = 1; $forkCount <= $forkCeiling; $forkCount++) { $pid = fork(); if ($pid) { push(@childArray, $pid); } elsif ($pid == 0) { # call the download subroutine and pass the number of forks, parent pid and array print "Sending fork number $forkCount to the \"process files\" subroutine...\n"; my $file = shift(@fileArray); print "DEBUG: $file \n"; procFiles($forkCount, $$, $file); exit 0; } else { die "couldnt fork: $!\n"; } } ## we will stand by here and wait for each of those pids to complete ## The log entry for each fork will go here. foreach (@childArray) { my $procId = waitpid($_, 0); print "LOG: process number $procId\n"; } print "Main Terminated\n"; sub procFiles { ## simulate delay in processing dissimilar files srand(); my $minDelay = 1; my $maxDelay = 2; my $timeDelay = int(rand($maxDelay)) + $minDelay; ## get the fork number, process id and filename my $forkCount = $_[0]; my $procId = $_[1]; my $fileName = $_[2]; ## get the process id for this fork my $processIDnum = shift; ## sleep $num; print "Completed child process ($procId), fork number $forkCount, file name $fileName\n"; ## retun the process id, which will be picked up return $processIDnum; }