in reply to Re: Reading from STDOUT after Redirecting it.
in thread Reading from STDOUT after Redirecting it.

It might be worth pointing out that re-opening STDOUT within your perl script will only affect stuff printed by that perl script and not the output from programs you spawn from within your perl script using system. They have their own set of file handles which are independant of those in your script.
I don't think that's true; the child process should inherit all the file handles.
  • Comment on Re: Re: Reading from STDOUT after Redirecting it.

Replies are listed 'Best First'.
Re: Re: Re: Reading from STDOUT after Redirecting it.
by sgifford (Prior) on Jul 03, 2003 at 06:20 UTC

    Child processes inherit all file descriptors, but a file handle is an internal Perl thing and isn't inherited in the way you'd expect.

    When a new process starts up, standard in is on file descriptor 0, standard out on file descriptor 1, and standard error on file descriptor 2. To redirect one of these, a Perl script has to assign a new file to one of these file descriptors. But that's not what happens by just reassigning STDOUT:

    #!/usr/bin/perl open(STDOUT,"> /tmp/t26.out");
    $ strace -e open perl /tmp/t26
    ...
    open("/tmp/t26.out", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
    
    Fortunately, it's not that hard to work around; open always returns the lowest numbered file descriptor, so closing STDOUT right before re-opening it will do what you expect:
    #!/usr/bin/perl close(STDOUT); open(STDOUT,"> /tmp/t27.out");
    $ strace -e open perl /tmp/t27
    ...
    open("/tmp/t27.out", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 1