Gossamer Forum
Home : General : Perl Programming :

Redirecting STDOUT and STDERR??

Quote Reply
Redirecting STDOUT and STDERR??
I'm in the process of writing a test tool in Perl for a product we're developing. I've re-directed the Perl STDERR to a logfile, which is logging Perl errors as expected. However, the application I'm testing writes some error messages to the console (STDOUT). I need to capture any application errors in a file (which I've partially done), because the test tool is designed to run overnight. I've done this by redirecting STDOUT to the log file. The trouble is, once I've re-directed STDOUT to the file, I'm unable to redirect it back to the console as it was before, to avoid sending everything to the log file.

Has anyone got any suggestions on how I could achieve this?

Regards,

Dan.
Quote Reply
Re: [danwarner] Redirecting STDOUT and STDERR?? In reply to
maybe try this:

Code:
my $prev = select STDERR; # redirect print requests to STDERR

# your code
print "this text will end up in stderr";

select $prev; # restore print requests to STDOUT

Look at perl's help docs on what the select function will do for you and what caveats to look for.
Quote Reply
Re: [Aki] Redirecting STDOUT and STDERR?? In reply to
Do you not need to flush the buffers before re-selecting the original filehandle?
Quote Reply
Re: [Paul] Redirecting STDOUT and STDERR?? In reply to
Not that I know of, a quick check of perldoc -f select doesn't seem to suggest something. I think he's fairly safe anyways, a quick test that would never of filled the buffer worked for me.

Code:
bash-2.05a$ perl -e 'select STDERR; print "f"; select STDOUT; sleep 10' > /dev/null
fbash-2.05a$
Quote Reply
Re: [Paul] Redirecting STDOUT and STDERR?? In reply to
Thanks for the suggestions. I tried them, but unfortunately they didn't quite do what I was trying to achieve. I've managed to get my hands on a copy of the Perl Cookbook where I found this:

#first, dup STDOUT

open (OLDSTDOUT, "&>STDOUT) or die "Couldn't dup STDOUT: $!";

#re-direct STDOUT to log

open (STDOUT, ">> $logfile") or die "Can't open $logfile: $!";

system "$executable";

close STDOUT;

#restore original STDOUT

open (STDOUT, "&>OLDSTDOUT) or die "Can't restore STDOUT: $!";

close OLDSTDOUT;



Regards,

Dan.
Quote Reply
Re: [danwarner] Redirecting STDOUT and STDERR?? In reply to
Just a small correction, it is >& and there is a missing double quote after the handle name.


open (OLDSTDOUT, ">&STDOUT") or die "Couldn't dup STDOUT: $!";



Kinetik