How can I reinitialize Perl's STDIN/STDOUT/STDERR?

Josh picture Josh · Aug 28, 2009 · Viewed 16.7k times · Source

I have a Perl script which forks and daemonizes itself. It's run by cron, so in order to not leave a zombie around, I shut down STDIN,STDOUT, and STDERR:

open STDIN, '/dev/null'   or die "Can't read /dev/null: $!";
open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!";
open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!";
if (!fork()) {
  do_some_fork_stuff();
  }

The question I have is: I'd like to restore at least STDOUT after this point (it would be nice to restore the other 2). But what magic symbols do I need to use to re-open STDOUT as what STDOUT used to be?

I know that I could use "/dev/tty" if I was running from a tty (but I'm running from cron and depending on stdout elsewhere). I've also read tricks where you can put STDOUT aside with open SAVEOUT,">&STDOUT", but just the act of making this copy doesn't solve the original problem of leaving a zombie around.

I'm looking to see if there's some magic like open STDOUT,"|-" (which I know isn't it) to open STDOUT the way it's supposed to be opened.

Answer

Hari picture Hari · Nov 12, 2009

# copy of the file descriptors

open(CPERR, ">&STDERR");

# redirect stderr in to warning file

open(STDERR, ">>xyz.log") || die "Error stderr: $!";

# close the redirected filehandles

close(STDERR) || die "Can't close STDERR: $!";

# restore stdout and stderr

open(STDERR, ">&CPERR") || die "Can't restore stderr: $!";

#I hope this works for you.

#-Hariprasad AJ