in reply to reuse STDOUT after it was closed

The documentation for "open" has some sample code that "saves, redirects, and restores STDOUT and STDERR using various methods".

#!/usr/bin/perl open my $oldout, ">&STDOUT" or die "Can't dup STDOUT: $!"; open OLDERR, ">&", \*STDERR or die "Can't dup STDERR: $!"; open STDOUT, '>', "foo.out" or die "Can't redirect STDOUT: $!"; open STDERR, ">&STDOUT" or die "Can't dup STDOUT: $!"; select STDERR; $| = 1; # make unbuffered select STDOUT; $| = 1; # make unbuffered print STDOUT "stdout 1\n"; # this works for print STDERR "stderr 1\n"; # subprocesses too open STDOUT, ">&", $oldout or die "Can't dup \$oldout: $!"; open STDERR, ">&OLDERR" or die "Can't dup OLDERR: $!"; print STDOUT "stdout 2\n"; print STDERR "stderr 2\n";

Replies are listed 'Best First'.
Re^2: reuse STDOUT after it was closed
by hangon (Deacon) on Mar 12, 2007 at 11:34 UTC

    Just wondering (spend too much time on a 'doz box), but would reopening STDOUT to /dev/tty work?

      The difference between restoring STDOUT and re-opening it to /dev/tty is the case where STDOUT wasn't originally connected to the user's terminal.

      For example, if the output was redirected to a file by the user starting the program, if STDOUT were restored any output after it was restored would go to the file; if it were re-opened to /dev/tty output would start out going to the file, but after STDOUT was re-opened further output would go to the terminal.

      It's not completely clear from the OPs question which behavior is desired, so it's quite possible opening /dev/tty is the right solution.