Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Perl output redirection 1

Status
Not open for further replies.

BMO

Programmer
Aug 20, 2001
7
0
0
GB
Hi,

I've redirected the output from my Perl script to a log file using code similar to this:

print "STDOUT 1";
warn "STDERR 1";
print "STDOUT 2";
warn "STDERR 2";

# redirect standard output
open my $oldout, ">&STDOUT" or die "Can't duplicate STDOUT: $!";
open my $olderr, ">&STDERR" or die "Can't duplicate STDERR: $!";
close STDOUT;
open STDOUT, ">$log_file" or die "Can't redirect STDOUT: $!";
close STDERR;
open STDERR, ">>&STDOUT" or die "Can't redirect STDERR: $!";
print "STDOUT 3";
warn "STDERR 3";
print "STDOUT 4";
warn "STDERR 4";

# restore the original standard output
close STDOUT;
open STDOUT, ">&$oldout" or die "Can't restore old STDOUT: $!";
close STDERR;
open STDERR, ">&$olderr" or die "Can't restore old STDERR: $!";

print "STDOUT 5";
warn "STDERR 5";
print "STDOUT 6";
warn "STDERR 6";


Although this works, when I look at the log file and the screen, all the STDOUT and STDERR messages are grouped together after the the original standard output/error has been redirected i.e. all STDERR lines are printed together first and then STDOUT lines after. The problem with this is I do not get to see the correct sequence of events if an error has occurred. Before STDOUT and STDERR are redirected, the output sequence is correct.

My output looks something like this:

STDOUT 1
STDERR 1
STDOUT 2
STDERR 2
STDERR 3
STDERR 4
STDERR 5
STDERR 6
STDOUT 3
STDOUT 4
STDOUT 5
STDOUT 6

Can anyone suggest how I can make sure that output to both log file and screen, after restoration, occurs in the exact order as they are printed?

TIA




 
You could try

Code:
select STDERR; $| = 1;      # make unbuffered
select STDOUT; $| = 1;      # make unbuffered

after each redirection, but I think that your OS shell also has some influence on buffering and timing issues and probably offers no guarantees.

"As soon as we started programming, we found to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs."
--Maurice Wilkes
 
Thanks very much, you're a star! The output now prints in the order I expected.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top