Getting stderr when using '-|'

From: bill (please_post_at_nomail.edu)
Date: 12/30/04


Date: Thu, 30 Dec 2004 05:52:41 +0000 (UTC)


I want to use exec($prog, @args) to execute a system command without
worrying about shell escapes, but I also want to capture both stdout
and stderr from this system command. If I only wanted stdout, I
could do something like this

die "Can't fork: $!" unless defined(my $pid = open(my $read_child, '-|'));

if ($pid == 0) {
  exec($prog, @argv) or die "Can't exec $prog: $!\n";
  exit 0; # superfluous
}

my $output = do { local $/ = undef;, <$read_child> };
close $read_child;
if ($?) {
  die "Child failed: $?"
}

In the code above, $output captures the stdout from the command
run through exec. But how does one capture stderr as well? Not
surprisingly adding the string '2>&1' to exec's arguments fails
because exec just passes this string along as one more argument to
$prog.

Any help would be much appreciated.

bill



Relevant Pages

  • splitting stderr/stdout without using file
    ... I need to capture stdout and stderr but without using files for the ... This script will be part of a logging function that is called ...
    (comp.lang.perl.misc)
  • Re: Capturing error msgs from output = `cmd`
    ... But could not capture the error. ... content of stdin, stdout and stderr just to inspect their contents, this is ... If, however, the command executed generates an error msg, the ...
    (comp.lang.ruby)
  • Re: zsh: STDERR to a variable?
    ... one wanted to capture both stderr *and* stdout. ... I meant capturing both stderr and stdout ... In my address everything before the first period is backwards; ...
    (comp.unix.shell)
  • RE: Capturing stdout and stderr without redirection
    ... Separate callback subs for STDOUT and STDERR... ... When all done, if array size> 0, fire off an email ... that, but is there a better, more elegant way to capture any ...
    (perl.beginners)
  • Re: Exceptions in embedded env.
    ... I notice that j.l.Exception does not have a LineNumber field. ... > There is no stdout or stderr that I have access to. ... > an output stream that I could capture... ...
    (comp.lang.java.programmer)