shortNumber
shortNumber

Reputation: 29

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;
}

Upvotes: 1

Views: 246

Answers (3)

JRFerguson
JRFerguson

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

Jens
Jens

Reputation: 72667

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

Upvotes: 0

TLP
TLP

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

Related Questions