open files are attributes of a process. after you fork, you have 2
processes, files locks, open handles, as well as pending signals and
such are not shared. ie, when you print to STDOUT in child, it's not the
same STDOUT you expect in parent. why not use a pipe?
#!/usr/bin/perl
use strict;
use warnings;
pipe READH, WRITEH;
fork() ? parent() : child();
sub parent
{
close(WRITEH);
open(FH, ">logifle") || die $!;
#-- 10 lines from child. 1k at a time.
#-- do NOT use <READH> here as it might
#-- block forever looking for newlines
print FH while(read READH, $_, 1024);
close(READH);
close(FH);
}
sub child
{
close(READH);
#-- 10 lines to parent
print WRITEH "line $_\n" for(1..10);
close(WRITEH);
}
__END__
$ more logfile
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10
Mumia W. wrote:
I can't seem to redirect STDOUT to a file before forking in my perl
program.
In the parent, I want to redirect STDOUT to 'logfile' then fork. In the
child, I want to print something. That something should end up in the
log file, but it's not working.
Here is my code:
use strict;
use warnings;
use constant EXIT_OK => 0;
$SIG{CHLD} = "IGNORE";
my $child = fork();
exit ($child ? parent() : child() );
sub parent {
close STDOUT;
open (STDOUT, '>', 'logfile') or die("Couldn't redirect STDOUT: $!\n");
EXIT_OK;
}
sub child {
print "Child's pid = $$.\n";
EXIT_OK;
}
__END__
This is my catch-22. I need to setup the redirection before I fork, but
I shouldn't redirect from within the child, and I can't find out if I am
the child or not until I've called fork :(
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>