#!/usr/bin/perl -w use strict; use POSIX qw(:signal_h :errno_h :sys_wait_h); sub sched{ my $file = shift || die "Missing parameter for subroutine call\n"; my $time = shift || die "Missing second parameter on subroutine call+\n"; my $chd = shift; sleep 5; my $cmd = `cat $file`; print " Child $chd in sched \n"; print $cmd; } # main program my $pid; # process id my $counter = 0; my %children; # Hashtable to hold all pids of our children my @childs; # will hold all pids of our children $SIG{CHLD} = sub{ my $pid; my $j = -1; $pid = waitpid(-1, &WNOHANG); if (WIFEXITED($?)) { # Remove the child that just died if($children{$pid}){; $j = $children{$pid}; delete $children{$pid}; delete $childs[$j]; print "Process $pid exited $j and $#childs\n"; } } }; $SIG{TERM} = sub{ kill -9, @childs; exit(0) }; # allow to end program by pressinc Ctrl-C or a kill call #this will hold all of our tasks my @tasks = ( { file => "msg.1", time => 10, }, { file => "msg.2", time => 2, }, { file => "msg.3", time => 5, }, ); # looping through the array of hashes and forking with each element my $j =0; FORLOOP: for my $i ( 0..$#tasks){ FORK: { if ($pid = fork){ # first fork # we are parent push @childs,$pid; $children{$pid} = $#childs; print "Parent forked child # ===> $#childs, pid = $pid \n"; next FORLOOP; }elsif (defined $pid){ # so we are a child print "Executing child $j \n"; sched($tasks[$i]{file},$tasks[$i]{time}, $j); print "Done! pid = $pid\n"; exit(0); }elsif ($! =~/No more process/){ sleep 5; redo FORK; }else{ die "Something is wrong: $!\n"; } } } print "started all children $#childs \n"; while ($#childs > -1 ){;} #Exit after all children are dead.