-> parent executes count
-> count creates child
<- parent exits
-> child executes count2
-> count2 creates grandchild
<- child exits
-> grandchild executes end of script
<- grandchild exits
####
my $PID = fork();
if ($PID) {
# in the parent process
}
else {
# in the child process
}
####
#!/usr/bin/perl
$f1="file1.txt";
$f2="file2.txt";
$f3="file3.txt";
$naptime=5;
sub count{
print "Starting Fork 1\n";
open(FILE1, ">$f1");
while($x < 10){
$x=$x+1;
print FILE1 "$x\n";
sleep($naptime);
}
close(FILE1);
}
sub count2{
print "Starting Fork 2\n";
open(FILE2, ">$f2");
while($y < 10){
$y=$y+1;
print FILE2 "$y\n";
sleep($naptime);
}
close(FILE2);
}
sub count3 {
print "Starting fork 3\n";
open(FILE3, ">$f3");
while($z < 10){
$z=$z+1;
print FILE3 "$z\n";
sleep($naptime);
}
close(FILE3);
}
my @funcs = (\&count, \&count2, \&count3);
print "Parent Script Started!\n";
foreach my $func (@funcs) {
my $PID = fork();
if ($PID) {
# we are in parent
wait;
}
else {
# we are in the child so excute the function
$func->();
# and exit when it is done
exit;
}
# back in parent here,.. and we loop
}
print "Parent Script Finished!\n";