Mayur Mayur - 1 month ago 7
Perl Question

Linux - Perl fork loop without exiting child process

I'm new to fork concept. I'm trying a simple script with fork loop expecting to execute twice but end up with 3 occurrence. is it because i did not exit the child process ? can you clarify please

script :

#!/usr/bin/perl

open(my $fh, '>', 'report.txt');
print $fh "before invoke fork \n";
close $fh;

@list = (1, 2);

foreach $a (@list){

if($pid = fork){
open(my $fh, '>>', 'report.txt');
print $fh "Parent process! $a $pid\n";
close $fh;

}else {
open(my $fh, '>>', 'report.txt');
print $fh "Child process $a $pid\n";
close $fh;
}
}


output:

before invoke fork
My second report generated by perl 1 1808
My second report generated by perl 2 1809
My thrid report generated by perl 2 0
My thrid report generated by perl 1 0
My second report generated by perl 2 1810
My thrid report generated by perl 2 0

Answer

It's because the point at which you fork() both processes start at exactly the same point.

So 'child 1' will continue to run, and continue through the loop, and run 'iteration 2'.

So parent will fork twice, child 1 will fork once, and child 2 - because it's the last loop iteration - will not fork at all.

I would suggest you really should consider Parallel::ForkManager because it simplifies this a lot. And also - turn on use strict; and use warnings. And don't use single letter variables, especially not $a.

Here's some example code of how to use Parallel::ForkManager.

However to address your problem - sticking a last in the child stanza will cause it to bail out of the loop.