Creating a child process in perl

Thursday, January 31, 2013 , , 0 Comments

This example fork 10 child processes.
It will wait for all child's to finish before exiting.


#!/usr/local/bin/perl

use strict;
use warnings;

print "Starting main program\n";
my @childs;

for ( my $count = 1; $count <= 10; $count++) {
        my $pid = fork();
        if ($pid) {
        # parent
        #print "pid is $pid, parent $$\n";
        push(@childs, $pid);
        } elsif ($pid == 0) {
                # child
                sub1($count);
                exit 0;
        } else {
                die "couldnt fork: $!\n";
        }
}
foreach (@childs) {
        my $tmp = waitpid($_, 0);
         print "done with pid $tmp\n";

}
print "End of main program\n";

sub sub1 {
        my $num = shift;
        print "started child process for  $num\n";
        sleep $num;
        print "done with child process for $num\n";
        return $num;
}


Output looks like:

Starting main program
started child process for  1
started child process for  2
started child process for  3
started child process for  4
started child process for  5
started child process for  6
started child process for  9
started child process for  10
started child process for  7
started child process for  8
done with child process for 1
done with pid 5584
done with child process for 2
done with pid 5585
done with child process for 3
done with pid 5586
done with child process for 4
done with pid 5587
done with child process for 5
done with pid 5588
done with child process for 6
done with pid 5589
done with child process for 7
done with pid 5590
done with child process for 8
done with pid 5591
done with child process for 9
done with pid 5593
done with child process for 10
done with pid 5594
End of main program

0 comments: