MichaelMeyer has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks! I'm about to write script to be used as a daemon. It's purpose is to check for a file every second and process it, if present. I use Daemon::Simple from CPAN to daemonize my script. Now my Problem is, when I use sleep() in my main loop no outputs at all are made (I write a logfile) - if I remove the sleep() statement, of course, the logfile is filled very rapidly. I just don't get it... what is the problem? Here's the code
use Daemon::Simple; $prog_name = 'some_prog'; ## Initialize Daemon ## my $homedir = '/'; my $pidfile = "/var/run/$prog_name.pid"; my $command = $ARGV[0]; Daemon::Simple::init($command,$homedir,$pidfile); ## Daemon script ## open LOG, ">>$log_file"; # $log_file contains an absolute path print LOG "$prog_name started."; ## Daemon Loop ## while (1) { print LOG "before sleep..."; sleep(1); print LOG "after sleep..."; } close LOG; __END__
Could anyone help out?

Replies are listed 'Best First'.
Re: Daemon problem with sleep()
by almut (Canon) on Dec 17, 2008 at 12:08 UTC
      Hi almut, you were right, it was a buffering problem with explicit flushing now it works. Thanks for the help!
        Even after proper flushing, don't forget to rotate your log file properly using log4perl or log::agent modules, otherwise your log file may reach the maximum allowed file size by the OS and soon it may lead to catastrophic situations.
Re: Daemon problem with sleep()
by zentara (Cardinal) on Dec 17, 2008 at 12:13 UTC
    Or instead of autoflushing, use a \n to force the flush.
    ## Daemon Loop ## while (1) { print LOG "before sleep...\n"; sleep(1); print LOG "after sleep...\n"; }

    I'm not really a human, but I play one on earth Remember How Lucky You Are

      I think newlines wouldn't help here, as the LOG handle isn't 'interactive' (such as when connected to a tty). Virtually anything else is by default block-buffered (as opposed to line-buffered in the interactive case).

      \n only flushes when writing to STDOUT and only when it's connected to a terminal. That's not the case here.

      Autoflushing can be turned on using

      use IO::Handle qw( ); LOG->autoflushing(1);

        Is that the same as $|++;?

        I'm so adjective, I verb nouns!

        chomp; # nom nom nom