Why doesn't this fork loop work as expected?

132 views Asked by At

Why does the following code:

#!/usr/bin/perl
use strict;
use warnings;
use Parallel::ForkManager;  

my $pm = new Parallel::ForkManager(5);

my @all_data = ('a','b','c','d','e','f');

foreach my $data (@all_data) {
    # Forks and returns the pid for the child:
    my $pid = $pm->start and next; 
    print "Hello $pid\n";
    $pm->finish; # Terminates the child process
}
$pm->wait_all_children;  

print:

Hello 0  
Hello 0  
Hello 0  
Hello 0  
Hello 0  

I am new to Perl and I am trying to catch up on multiprocessing in Perl

2

There are 2 answers

2
amon On BEST ANSWER

From the docs for the start method:

This method does the fork. It returns the pid of the child process for the parent, and 0 for the child process.

As it happens, the fork function does the same, which is why start mirrors it.

The parent may need the child PID to control the child – sending signals and stuff – but the child knows its own PID via the $$ variable:

foreach my $data (@all_data) {
    $pm->start and next; 
    print "Hello $$\n";
    $pm->finish;
}

Example output:

Hello 22215
Hello 22218
Hello 22219
Hello 22217
Hello 22220
Hello 22216
2
dwindura On

my $pid = $pm->start and next;

"and" logic will evaluate to true if both of the arguments are true. If the first argument is false, then the "and" logic will shortcut and will not evaluate the second argument

You might want to use "or" logic instead.