develooper Front page | perl.perl5.porters | Postings from January 2013

Re: [perl #116589] open2 acts very strange when STDOUT is redirected.

Thread Previous
From:
Dave Mitchell
Date:
January 30, 2013 20:23
Subject:
Re: [perl #116589] open2 acts very strange when STDOUT is redirected.
Message ID:
20130130202344.GU2066@iabyn.com
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

Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About