in reply to Help with multiple forks
use strict; use warnings; my @array1 = (1..4); my @array2 = (1..4); for my $val1 (@array1) { my $outer_pid = fork(); die "fork failed ($val1)" unless defined $outer_pid; if ($outer_pid == 0) { open my $fh, ">", "$val1.txt" or die "Open fail: $!"; print $fh "Output of step 1\n"; exit 0; } else { waitpid $outer_pid, 0; for my $val2 (@array2) { my $inner_pid = fork(); die "fork failed ($val1,$val2)" unless defined $inner_pid; if ($inner_pid == 0) { open my $fh1, '<', "$val1.txt" or die "Open fail: $!" +; open my $fh2, ">", "$val2$val1.txt" or die "Open fail +: $!"; while (my $line = <$fh1>) { $line =~ s/1/2/; print $fh2 $line . "\n"; } exit 0; } else { waitpid $inner_pid, 0; } } } }
Update: It occurs to me that you likely don't want a blocking wait on your children, since this is specifically not generating simultaneous workers. You have a potential race condition in that scenario, since generating the first set of files may take more time than is required to get to generating the second set. You can resolve this in classic style using flock. You can also just ignore the problem of reaping kids using local $SIG{CHLD} = 'IGNORE';. The following code includes a 1 second sleep in the first loop to demonstrate blocking, and generates 21 simultaneous processes at max:
use strict; use warnings; use Fcntl ":flock"; my @array1 = (1..4); my @array2 = (1..4); local $SIG{CHLD} = 'IGNORE'; for my $val1 (@array1) { my $pid = fork(); die "fork failed ($val1)" unless defined $pid; if ($pid == 0) { open my $fh, ">", "$val1.txt" or die "Open fail: $!"; flock($fh, LOCK_EX) or die "Cannot lock $val1.txt - $!\n"; print $fh "Output of step 1\n"; sleep 1; flock($fh, LOCK_UN) or die "Cannot unlock $val1.txt - $!\n"; exit 0; } } for my $val1 (@array1) { for my $val2 (@array2) { my $pid = fork(); die "fork failed ($val1, $val2)" unless defined $pid; if ($pid == 0) { open my $fh1, '<', "$val1.txt" or die "Open fail: $!"; flock($fh1, LOCK_SH) or die "Cannot lock $val1.txt ($val2) + - $!\n"; open my $fh2, ">", "$val2$val1.txt" or die "Open fail: $!" +; while (my $line = <$fh1>) { $line =~ s/1/2/; print $fh2 "$line\n"; } flock($fh1, LOCK_UN) or die "Cannot unlock $val1$val2.txt +- $!\n"; exit 0; } } }
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
|
|---|