if doesn't just check for fork returning undef; it also checks for returning 0, which is what fork does in the child. From the manual:
(fork) returns ... 0 to the child process,

So this code is creating three processes:

When the grandchild finishes, its parent is already gone, so it's been reparented to init, which notices its death and waits for it, avoiding a zombie.

The OP's problem is that he's waiting for the child but running the long-running process in the grandchild. The fix is to eliminate the second fork, and just do the work in the child; the purpose of a second fork is to do something in the background without having to wait for it, which is what the OP is trying to avoid.

Here's a small example:

warn "PID $$ (parent) forking\n"; unless ($pid = fork) { warn " PID $$ (child) forking again\n"; unless (fork) { warn " PID $$ (grandchild) exec'ing\n"; exec "sleep 5"; die "Couldn't run getSite.pl"; exit 0; } warn " PID $$ (child) exiting\n"; exit 0; } warn "PID $$ (parent) executing waitpid\n"; waitpid($pid,0); warn "PID $$ (parent) done.\n";
outputs:
PID 6083 (parent) forking
  PID 6084 (child) forking again
    PID 6085 (grandchild) exec'ing
  PID 6084 (child) exiting
PID 6083 (parent) executing waitpid
PID 6083 (parent) done.

Here's a version which does what I believe the OP wants.

warn "PID $$ (parent) forking\n"; unless ($pid = fork) { warn " PID $$ (child) exec'ing\n"; exec "sleep 5"; die "Couldn't run getSite.pl"; } warn "PID $$ (parent) executing waitpid\n"; waitpid($pid,0); warn "PID $$ (parent) done.\n";

But, this is completely equivalent to system, so why not just use that?


In reply to Re^4: Waiting for an External Program to Finish Executing by sgifford
in thread Waiting for an External Program to Finish Executing by awohld

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.