7stud has asked for the wisdom of the Perl Monks concerning the following question:
Dear Monks,
According to perlfork:
Lifetime of the parent process and pseudo-processes
During the normal course of events, the parent process and every pseudo-process started by it will wait for their respective pseudo-children to complete before they exit.
However, when I call fork, and the parent does nothing and terminates, the child does not finish executing. For example, in the following program a child writes to a file every 2 seconds:
use strict; use warnings; use 5.010; my $child_pid = fork; $| = 1; if (!defined $child_pid) { say "**My error**: couldn't fork: $!"; } if ($child_pid) { #then in parent say "in parent..."; sleep 1; } else { #then in child open my $OUTFILE, '>', 'data1.txt' or die "**My error: couldn't open data1.txt: $!"; for (1 .. 10) { say $OUTFILE $_; sleep 2; } close $OUTFILE; }
...and the output is:
$ perl 1perl.pl in parent... $ cat data1.txt $
In other words, nothing gets written to the file--usually. About one in ten tries, this is the output:
$ perl 1perl.pl in parent... $ cat data1.txt 1 2 3 4 5 6 7 8 9 10 $
Can someone explain what is supposed to happen when the parent terminates before the child finishes executing?
|
---|