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?


In reply to fork(): when parent exits, what happens to child? by 7stud

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.