[prev in list] [next in list] [prev in thread] [next in thread]
List: perl5-porters
Subject: Re: [perl #116589] open2 acts very strange when STDOUT is redirected.
From: Dave Mitchell <davem () iabyn ! com>
Date: 2013-01-30 20:23:44
Message-ID: 20130130202344.GU2066 () iabyn ! com
[Download RAW message or body]
On Tue, Jan 29, 2013 at 10:38:14PM -0800, Xungeng Lee wrote:
> see this example:
> xungeng@debian:~/work/test/test$ cat foo
> #!/usr/bin/perl
> use FileHandle;
> use IPC::Open2;
> use IO::Handle;
>
> #*STDOUT = IO::Handle->new;
>
> for (1..3) {
> print STDERR "Loop: $_\n";
> $pid = open2( \*Reader, \*Writer, "cat" );
> Writer->autoflush(); # default here, actually
> print Writer "stuff\n";
> $got = <Reader>;
> print STDERR $got;
> }
> xungeng@debian:~/work/test/test$ cat bar
> #!/usr/bin/perl
> use FileHandle;
> use IPC::Open2;
> use IO::Handle;
>
> *STDOUT = IO::Handle->new;
>
> for (1..3) {
> print STDERR "Loop: $_\n";
> $pid = open2( \*Reader, \*Writer, "cat" );
> Writer->autoflush(); # default here, actually
> print Writer "stuff\n";
> $got = <Reader>;
> print STDERR $got;
> }
> xungeng@debian:~/work/test/test$ ./foo > /dev/null
> Loop: 1
> stuff
> Loop: 2
> stuff
> Loop: 3
> stuff
> xungeng@debian:~/work/test/test$ ./bar > /dev/null
> Loop: 1
> Loop: 2
> Loop: 3
>
> the difference between foo and bar is only that STDOUT redirected or not.
>
> when STDOUT is redirected, open2 make the child process write to the old
> STDOUT,
> not the child_out handler (\*Reader in this example).
Well for stdout, IPC::Open3 (which IPC::Open2 calls out to) does
essentially:
pipe(\*Reader, \*FOO);
fork();
if (child) {
close(Writer);
open(STDOUT, ">&=" . fileno(FOO));
exec($cmd);
}
i.e. it dups the file handle of the pipe to whatever file handle STDOUT
maps to. If STDOUT doesn't point to file handle 1, then it won't work.
I don't understand Open3.pm enough to decide whether it's unreasonable for
it to handle a non-1 STDOUT (etc) or not.
--
Any [programming] language that doesn't occasionally surprise the
novice will pay for it by continually surprising the expert.
-- Larry Wall
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic