Getting stderr when using '-|'

B

bill

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
 
K

KKramsch

In said:
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
 
P

Paul Lalli

bill said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top