On Thu, Jul 2, 2009 at 04:36, Eric Veith<erve...@de.ibm.com> wrote:
>
> Hello List,
>
> as part of a Perl script of mine, I want to execute a program, get its
> return code AND capture its output on both STDERR and STDOUT. I tried
> IO::Handle, but that only gives me STDOUT and not the return code. Using
> qr//, I cannot read linewise and have to load the complete program's output
> into memory first, which I want to avoid. (Please feel free to correct me
> on anything of the above.)
>
> What I tried to archive now can be summarized in this little script:
>
> my $stdout = IO::File->new('stdout', 'w');
> my $stderr = IO::File->new('stderr', 'w');
>
> my $pid = fork();
> die("Could not fork, stopping") if(not defined $pid);
>
> if(0 == $pid) {
>    *STDOUT = $stdout;
>    *STDERR = $stderr;
>    system("df", "-h");
>    my $rc = $?;
>    $stdout->flush(););
>    exit($rc << 127););
> } else {
>    print "Parent.\n";;
>    wait();
>    print "RC=$?\n";
> }
>
> $stdout->close();
> $stderr->close();
>
>
> That does not, however, work as expected. I do get STDERR's output (if I,
> for example, change the command in system() to something that does not
> work, e. g. system("df", "garbage", "-FOO"); the error is to be found in
> the stderr file), but not the output on STDOUT -- that is printed out on
> screen just as usual.
>
> What am I missing here? How can I do a fork, re-open STDOUT/STDERR to write
> to an instance of IO::Handle, and get the return code?
>
> Thanks for any hints.
>
>            -- Eric
>
>
> --
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
>
>
>

You need [IPC::Open3][1].  It allows you to run a command and capture
the STDOUT, STDERR, and (via the [$?][2] variable).  Here is an
example:

#!/usr/bin/perl

use strict;
use warnings;

use IPC::Open3;

#the program gets run by itself with an argument
if (@ARGV) {
        print "this went to STDOUT\n";
        print STDERR "this went to STDERR\n";
        exit 55;
}

my $err = 1; #err handle must be true or it gets combined into out
my $pid = open3 my $in, my $out, $err, $^X, $0, 1
        or die "could not run '$^X $0 1': $!";

waitpid $pid, 0; #wait for program to finish;
my $return_code = $? >> 8;
my $stdout      = join "", <$out>;
my $stderr      = join "", <$err>;

print "I saw $return_code as the return code\n",
        "and [$stdout] on STDOUT and [$stderr] on STDERR.\n";


[1] : http://perldoc.perl.org/IPC/Open3.html
[2] : http://perldoc.perl.org/perlvar.html#$?

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to