in reply to Shared file-handles & fork fun
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}
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Shared file-handles & fork fun
by kabeldag (Hermit) on Nov 22, 2006 at 21:16 UTC |