Search code examples
perl

Unable to redirect stdout and stderr to output file


I have a Perl script that needs to run as a daemon. I am setting a few environment variables in a shell script and calling the Perl script from there.

This is a simplified version of the script:

#!/usr/bin/env perl
do {
    print "HELLO";
    print "TO";
    print "HELL";
    #sleep (10);
} while (1)

This is a simplified version of my shell script:

#!/usr/bin/ksh

DATE=`date +'%Y%m%d'`
TIME=`date +'%H%M%S'`
PID=$$
tmp_log_file=${PID}_${DATE}_${TIME}.log
abcd.pl >>$tmp_log_file &

If I comment out the sleep function call from perl, it works fine. But, when I uncomment it, the tmp_log_file is created as zero bytes.

Perl Version : v5.10.0

KSH Version : version sh (AT&T Research) 93t+ 2010-02-02

Any clues?


Solution

  • Are you Suffering from Buffering?

    If so, the data will eventually appear in the log file (unless the program is killed), but you can make it appear there sooner by adding the following to the top of your Perl code:

    $| = 1;
    

    The special variable $| (also called $OUTPUT_AUTOFLUSH) will force output to be flushed with every write if its value is non-zero. Follow the link to see how to set autoflush per filehandle.