While reading the cookbook, I started playing with the forking open. I have a small program (below) that forks 3 processes, each of which modify STDIN and send to STDOUT. What I don't understand is why they work in the order that they do.
tee('foo');
tee('bar');
tee('baz');
while (<>) { print }
sub tee {
my $key = shift;
# reopen STDOUT in parent and return
return if my $pid = open(STDOUT, "|-");
die "cannot fork: $!" unless defined $pid;
$|++;
# process STDIN in child
while (<STDIN>) {
print "$key: $_" or die "tee output failed: $!";
}
print "$$ exiting...\n";
exit; # don't let the child return to main!
}
When the first child is forked, the STDOUT of the parent is connected to the STDIN of the child, like so:
Parent -> Child1
For the second and third forks I would expect the new child to be inserted between the parent and current child, so that after 3 forks:
Parent -> Child3 -> Child2 - Child1
So I would expected each line of output to be preprended with:
baz: bar: foo:
Instead, each line of output is prepended with:
foo: bar: baz:
What is the error in my reasoning? How does this actually work?
Thanks.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.