Reputation: 29
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;
}
Upvotes: 1
Views: 246
Reputation: 7526
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.
Upvotes: 3
Reputation: 67890
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.
Upvotes: 4