Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirecting stdin/stdout from exec'ed process to pipe in Perl

I am trying to have STDOUT/STDERR from a exec'ed child process go back to the parent via a pipe in Perl. The closest I have seen to what I want to do is at : http://forums.devshed.com/perl-programming-6/exec-and-redirecting-stdout-stderr-168501.html

The following is a stripped down example of what I am trying to do. I also tried a variant of the link above. I can't see what I'm doing wrong...

#!/usr/bin/env perl

use strict ;
use warnings ;

my $cmd    = "/usr/bin/who -a" ;  # anything to stdout

pipe( READER, WRITER ) ;
my $child = fork() ;
if ( $child ) {
    print "I am the parent: My pid = $$ junior = $child\n" ;
    close( WRITER ) ;
    my @output = <READER> ;
    print @output ;
    print "parent is DONE\n" ;
} else {
    print "I am the child. My pid = $$\n" ;

    close( READER ) ;
    close( STDOUT );
    close( STDERR );
    *STDOUT = *WRITER ;
    *STDERR = *WRITER ;

    print WRITER "XXX ouput before exec....\n" ;

    exec( $cmd ) or exit(1) ;
}
like image 671
RJ White Avatar asked Aug 18 '13 02:08

RJ White


1 Answers

It's not possible to redirect file descriptors just with assignments. Rather one needs to use open like described in perldoc -f open. In your case the child code would look like this:

    print "I am the child. My pid = $$\n" ;

    close( READER ) ;

    open STDOUT, ">&", \*WRITER or die $!;
    open STDERR, ">&", \*WRITER or die $!;

    print WRITER "XXX ouput before exec....\n" ;

    exec( $cmd ) or exit(1) ;
like image 138
Slaven Rezic Avatar answered Oct 16 '22 05:10

Slaven Rezic