For Programmers: Free Programming Magazines  


Home > Archive > PERL Miscellaneous > December 2004 > Getting stderr when using '-|'









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Getting stderr when using '-|'
bill

2004-12-30, 3:57 am






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


KKramsch

2004-12-30, 3:57 am

In <cr0539$so4$1@reader1.panix.com> bill <please_post@nomail.edu> writes:

>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) {


open (STDERR, '>&STDOUT') or die "Can't dup STDOUT\n";

> 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: $?"
>}




HTH,

Karl

--
Sent from a spam-bucket account; I check it once in a blue moon. If
you still want to e-mail me, cut out the extension from my address,
and make the obvious substitutions on what's left.
Paul Lalli

2004-12-30, 8:57 am

"bill" <please_post@nomail.edu> wrote in message
news:cr0539$so4$1@reader1.panix.com...
>
> 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.



Have you read the appropriate FAQ on this topic?
perldoc -q stderr


Paul Lalli

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com