0

I have searched the internet for different solutions and the closest I have done is an exercise in open statements:

use strict;
use warnings;
use Carp;

# Save previous state
my ($old_out, $old_err);

open($old_out, ">&", \*STDOUT) or 
    croak("Cannot save STDOUT: $!\n");
open($old_err, ">&", \*STDERR) or 
    croak("Cannot save STDERR: $!\n");

my ($fh_OUTLOG);
# Make a filehandle for the tee output
open($fh_OUTLOG, "|-", "tee out_err.log") or
    croak("Cannot open filehandle to tee to log file: $!\n");

# Duplicate STDOUT and STDERR to the filehandle
open(STDOUT, ">&", $fh_OUTLOG) or
    croak("Cannot duplicate STDOUT to filehandle: $!\n");

open(STDERR, ">&", $fh_OUTLOG) or
    croak("Cannot duplicate STDERR to filehandle: $!\n");

# Code...


# Restore STDOUT 
open(STDOUT, ">&", $old_out) or
    croak("Cannot restore STDOUT: $!\n");

# Close the filehandle            
close $fh_OUTLOG        
    or croak( ($!) ? "Error closing fh_OUTLOG: $!"
                  : "Exit status $? from tee log.out");

# Restore STDERR   
open(STDERR, ">&", $old_err) or
     croak("Cannot restore STDERR: $!\n");

But this code will not produce an log file with STDERR, and I dont know how to add it. The criteria for the solution are:

  1. Perl v 5.8.3.
  2. No CPAN modules.
  3. No Bash extra command to start the script.

I was thinking of using some teesolutions for STDERR as well:

open(STDERR, "| tee log.err");
open(STDERR, ">&", $fh_OUTLOG);

But using this will hang the script in the end of the execution. (Think the tee child process still is alive). But the script still hangs if I try to kill it in the end.

my $pid_std_err = open(STDERR, "| tee log.err") or
     croak("Cannot tee filehandle STDERR to log.err: $!\n");

# Code... 

kill -9, $pid_std_err;
crlb
  • 1,282
  • 12
  • 18
  • Why are you banning CPAN modules? It's like you don't actually want to write Perl code after all. Perl is all about taking the right pre-built pieces and just glueing them together. If you wanted to write it yourself from scratch, go write it in C or something – LeoNerd Mar 21 '14 at 13:32
  • Wish I could install CPAN modules but in this project it is not possible. – crlb Mar 21 '14 at 13:41
  • 1
    How is it you can install code from SO but not from CPAN? What happens if I copy something from CPAN to SO? – ikegami Mar 21 '14 at 13:42
  • If you can put Perl code in a file on the server and run it, you can install Perl modules. They can be installed anywhere. – Brad Gilbert Mar 23 '14 at 02:34

1 Answers1

0
  1. Create two pipes and associate them wih STDOUT and STDERR.
  2. Create a task (thread, process, etc) that uses IO::Select to read from those two pipes.
  3. The task places what it reads from those pipes in the appropriate files(s).
ikegami
  • 367,544
  • 15
  • 269
  • 518