This fails because the open() makes STDERR go to where STDOUT was going at the time of the open(). The backticks then make STDOUT go to a string, but don't change STDERR (which still goes to the old STDOUT).
So don't use backticks. Redirect STDOUT to a file, redirect STDERR to STDOUT and use system() instead.
use strict;
use warnings;
use File::Temp;
my $temp_stdout = File::Temp->new;
local *OLDOUT;
local *OLDERR;
open( OLDOUT, ">&STDOUT" );
open( OLDERR, ">&STDERR" );
open( STDOUT, ">$temp_stdout" );
open( STDERR, ">&STDOUT" );
# Funky quoting for Windows. Sigh.
system('perl -e "print q{to stdout}; warn q{to stderr}; print q{more t
+o stdout}');
close(STDOUT);
open(STDOUT, ">&OLDOUT");
open(STDERR, ">&OLDERR");
open CAPTURED, "<$temp_stdout";
my $capture = do { local $/; <CAPTURED> };
close CAPTURED;
print "Got this:\n$capture";
That still doesn't solve the problem of keeping them in sync because the subprocess still has two buffered handles. The fact that they go to the same place doesn't matter. You need to get the child process to turn off buffering.
-xdg
Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|