2

Possible Duplicate:
How do you capture stderr, stdout, and the exit code all at once, in Perl?
Capturing the output of STDERR while piping STDOUT to a file

I am using the following piece of code to execute a process:

open( my $proch, "-|", $command, @arguments );

Unfortunately, I will just read the stdout. But I'd like to read the stderr as well.

Stderr redirection leads to the following error:

open( my $proch, "2>&1 -|", $command, @arguments );
>>> Unknown open() mode '2>&1 -|' at file.pl line 289

How can I forward stderr to stdout?

Community
  • 1
  • 1
JMW
  • 7,151
  • 9
  • 30
  • 37

1 Answers1

5

2>&1 is part of a shell command, but you didn't execute a shell.

open( my $proch, "-|", 'sh', '-c', '"$@" 2>&1', '--', $command, @arguments );

If you want to avoid spawning the extra process, you could use the following:

use IPC::Open3 qw( open3 );

open local *CHILD_STDIN, '<', '/dev/null') or die $!;
my $pid = open3(
   '<&CHILD_STDIN',
   \local *PROCH,
   undef, # 2>&1
   $command, @arguments
);

while (<PROCH>) { ... }

waitpid($pid, 0);
ikegami
  • 367,544
  • 15
  • 269
  • 518