Glad I could be of assistance!

Regarding your question, the magic occurs in the first line of run_shell. When open is called with "-|" as its file argument, it does something special: It forks the current process into two processes (parent and child) that run in parallel.

The parent process is the same as the original process. It receives in $pid the child's process ID, and its $pipe variable contains a filehandle that can read from the STDOUT of the child process.

The child process – and this is where it gets interesting – is running in parallel to the parent. The only difference is that in the child, the pid returned from open and stored in its copy of $pid is zero.

So now we have the parent and the child running in parallel. The first thing they both do is check the value of $pid to figure out which is parent and which is child. If $pid non-zero, the one process then knows that it is the parent, and it can package up the information it received about the child from open and return the package to the original caller. If $pid is zero, the other process knows it is the child and then ties its STDOUT to STDERR, starts a new process group, and then uses exec to replace its own process image with that of the command we gave to run_shell as arguments.

Thus, when run_shell returns, we have the following situation:

I hope that explanation clears things up.

Cheers,
Tom


In reply to How the hidden magic does its stuff by tmoertel
in thread Killing all processes launched using open() by SmilingBuddha

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.