You seem to be mixing concepts.

First, read open again. If you use a piped open, it will return the PID of the child process:

my $pid = open my $fh, "| $some_program" or die "Can't run '$some_program': $!\n";

Second, you will only need IPC::Open2 to write and read to/from the child process, but in your script I don't see you're attempting to read. open2 will also return a PID, and it will handle all that fork stuff and plumbing the pipes for you, so you don't need to fork.

Third: if you open a filehandle in the child after forking, it is visible in the child only. If you open it before forking, the file will be open in both parent and child:

#!/usr/bin/perl -w use strict; open(O,'>', "$$.tmp"); select O; $| = 1; # make output unbuffered print STDOUT "file is $$.tmp\n"; $SIG{'CHLD'} = \&reap; if ( (my $pid = fork()) == 0 ) { sleep 1; print "child ($$) here\n"; close O; exit 0; } else { print "parent ($$) here\n"; sleep 2; print "parent ($$) waking up..\n"; } sub reap { my $pid = wait; print "reaped PID $pid\n"; } __END__ file is 4782.tmp
$ cat 4782.tmp parent (4782) here child (4783) here reaped PID 4783 parent (4782) waking up..

Note that you must set $| = 1 for your filehandle to make output unbuffered if you want to keep the output of parent and child in order. Or better use IO::File and set autoflush FH 1.

--shmem

_($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                              /\_¯/(q    /
----------------------------  \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

In reply to Re: Shared file-handles & fork fun by shmem
in thread Shared file-handles & fork fun by kabeldag

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.