Forking in Perl

Foreach item in the array, start a fork. $pid returns 0 if it is the child process. This way you can spawn 4 child processes from one parent. This page explains it all and the code shown below is an adaptation of code shown from the link. I just added code to show the current process id and the process id of the child.


use strict;
use warnings;

my @seq = qw/one two three four/;

my @childs = ();

warn "Starting on $$\n";

foreach my $seq (@seq){
   print "#$seq\n";
   my $pid = fork();
   warn "Currently $$: created new fork on $pid\n";
   if ($pid) {
      # parent
      warn "\tPushing $pid into array\n";
      push(@childs, $pid);
   } elsif ($pid == 0) {
      # child
      warn "\tRunning child process for $seq\n";
   } else {
      die "Couldn't fork: $!\n";

foreach my $pid (@childs) {
   waitpid($pid, 0);

print "Done\n";
Print Friendly, PDF & Email

Creative Commons License
This work is licensed under a Creative Commons
Attribution 4.0 International License
2 comments Add yours

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.