in reply to fork : distinguish between different child?

Here's one way. I'm sure others will be along shortly.

#!/usr/bin/env perl use strict; use warnings; my @dirs = (qw/dir1 dir2 dir3 dir4/); my @kids; for my $i (1..4) { my $pid = fork(); if ($pid) { # parent push @kids, $pid; print "spawned child $pid\n"; } elsif ($pid == 0) { print "I am child $$. \@kids count = $#kids. my dir is $dirs[$#kid +s+1]\n"; sleep 5; exit(0); } else { die "couldn.t fork: $! \n"; } print "end loop $i\n"; } for my $pid (@kids) { print "reaping $pid\n"; waitpid($pid,0); }

Output:

I am child 20199. @kids count = -1. my dir is dir1 spawned child 20199 end loop 1 I am child 20200. @kids count = 0. my dir is dir2 spawned child 20200 end loop 2 I am child 20201. @kids count = 1. my dir is dir3 spawned child 20201 end loop 3 I am child 20202. @kids count = 2. my dir is dir4 spawned child 20202 end loop 4 reaping 20199 reaping 20200 reaping 20201 reaping 20202