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?
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:$!";
open LOG,">>/dev02/ycq/test/log" ||die "can not open file:$!";
print LOG "$num\n";
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 ...);
"file.txt" is a true statement, it will never trigger the
What you need is either:
open(LOG, "file.txt") || die ...
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.
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