Redirecting STDERR to STDOUT in Perl:
open STDERR, '>&STDOUT';
Reassign raw file handles:
*STDERR = *STDOUT;
Redirect all output to a logfile:
open(LOG,">/tmp/foo.log"); *STDERR = *LOG; *STDOUT = *LOG;
Example:
#!/usr/bin/perl use strict; use warnings; warn "regular error"; open STDERR, '>&STDOUT'; warn "redirected error";
Output:
[kitamura@web3 perl]$ ./stderr.pl 2>/dev/null redirected error at ./stderr.pl 6.
Hello,
Think about this code in context of redirecting STDOUT, STDERR:
#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw(:errno_h ceil floor :sys_wait_h);
my @run = ( ‘ls’, ‘-al’ );
my $pid = fork();
die “Unable to fork $!” unless defined($pid);
if (!$pid) { # child
open(LOG,”>”, “foo-log.log”);
#close(STDERR);
#close(STDOUT);
#open STDERR, “>>&LOG”;
#open STDOUT, “>>&LOG”;
*STDERR = *LOG;
*STDOUT = *LOG;
print LOG “PRINT TO LOG\n\n”;
exec { $run[0] } @run;
die “Unable to execute: $!”;
}
waitpid($pid, WNOHANG);
and output is shown on terminal not in log file:
but when running this:
#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw(:errno_h ceil floor :sys_wait_h);
my @run = ( ‘ls’, ‘-al’ );
my $pid = fork();
die “Unable to fork $!” unless defined($pid);
if (!$pid) { # child
open(LOG,”>”, “foo-log.log”);
close(STDERR);
close(STDOUT);
open STDERR, “>>&LOG”;
open STDOUT, “>>&LOG”;
#*STDERR = *LOG;
#*STDOUT = *LOG;
print LOG “PRINT TO LOG\n\n”;
exec { $run[0] } @run;
die “Unable to execute: $!”;
}
waitpid($pid, WNOHANG);
Everything is ok, maybe you know why:
*STDERR = *LOG;
*STDOUT = *LOG;
doesn’t work?