当前位置: 动力学知识库 > 问答 > 编程问答 >

When I create a daemon with perl and write something to a file, it fails

问题描述:

I use daemonize to create a daemon process and then write something to the file named log,

but when I ran it, it did not work.

Why could I not write to the log?

use POSIX;

sub daemonize{

chdir '/';

umask 0;

open STDIN,'/dev/null' || die "can not open /dev/null:$!";

open STDOUT,'>/dev/null' || die "can not open /dev/null:$!";

open STDERR,'>/dev/null' ||die "can not open /dev/null:$!";

defined ($pid=fork) || die "can not fork a process:$!";

exit if $pid;

setsid || die "can not create session:$!";

}

&daemonize;

open LOG,">>/dev02/ycq/test/log" ||die "can not open file:$!";

my $num=0;

while(1){

print LOG "$num\n";

sleep 1;

}

网友答案:

When using open (or any other function or subroutine), you need to take into consideration the operator precedence. In your case, the || operator has higher precedence than the , (comma) operator.

Your lines that look like this:

open LOG, "file.txt" ||die "can not open file:$!";

Actually mean this, when precedence is taken into consideration:

open LOG, ("file.txt || die ...);

Since "file.txt" is a true statement, it will never trigger the die statement.

What you need is either:

open(LOG, "file.txt") || die ...

or

open LOG, "file.txt" or die ...

In the first case, the parens override the operator precedence, in the second case, the or operator has lower precedence than the comma operator.

What all this means is that your open calls may have failed silently.

网友答案:

Exactly what error(s) do you get? You may be suffering from buffering .

You should use the 3-argument forms of open.

Your chdir isn't going to put you where you think; you have written ' /' with leading whitespace.

You might find Proc::Daemon useful, too.

网友答案:

And maybe because there's an extra space in chdir(' /').

分享给朋友:
您可能感兴趣的文章:
随机阅读: