Perl: Running a "Daemon" and printing
I am running a script that runs 24/7. It just loops through over and over, very simple:
while ($daemon) {
sleep 60;
chomp(my $currentDate = `date +%c`);
print LOG "--开发者_运维问答 Running trigger: $currentDate --\n";
system("$triggerCmd >> $daemonLog");
print LOG "-- Completed trigger test. --\n\n";
}
It works fine. The problem is that it doesn't print the last line ("Completed trigger test") until AFTER the 60 second sleep. It prints the running line, runs the command, prints command output, but then waits 60 seconds before printing "completed" and instantly printing "running" line again.
So the process it's following is this:
sleep 60 seconds print "running trigger" run trigger, redirect output sleep 60 seconds print completed print running run triggerBut I want it to do this:
sleep 60 print "running trigger" run trigger, redirect output print "completed" sleep 60I've tried moving the sleep command to the end of the loop, didn't make a difference. While this seems very minor, it's actually a problem I've been dealing with for a while and it would solve a few issues to fix it. I was rececntly using backticks to run the command and capture the output, then print output, but this resulted in the same behavior.
Possibly the output to LOG
is being buffered. Try
select LOG;
$| = 1;
select STDOUT;
or
use IO::Handle;
(*LOG)->autoflush(1);
after LOG
is initialized.
精彩评论