JamieD has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

Im trying to Daemonize my script and then open a file and write to it. The script works fine if I open the file then daemonize the script but it fails to run when I daemonize then open the file but I get no errors.

Heres the script im using:


# deamonize the server
Proc::Daemon::Init;


#open FDserv.p and write in the process id number
my $pid = POSIX::getpid();


open FILE, "FDserv.p" or die "Couldn't open: $!";
my @fileArray = <FILE>;
close FILE;

open FILE, ">FDserv.p" or die "Couldn't open: $!";
foreach(@fileArray){
	if(/id=(.*)/){
		print FILE "id=".$pid.";";
	}else{
		print FILE $_;
	}
}

close FILE;

Replies are listed 'Best First'.
Re: Daemonize and open a file
by rob_au (Abbot) on Dec 06, 2002 at 05:48 UTC
    (Disclaimer - I'm typing this reply from a terminal window using lynx so my formatting and layout may appear absolutely horrible)

    The problem here that I can see, from the code snippet provided is the path being passed to the open statement. The normal behaviour of Proc::Daemon as part of the initialisation process is to chdir to the root directory - This will greatly impact upon your script if relative paths are being used. The most likely thing that is happening here is that your script, finding itself in the root directory, cannot open the file FDserv.p and is ceasing execution. The reason why this is not returning an error to your screen from the die statement is because all open filehandles, including STDOUT, STDIN and STDERR, are closed by Proc::Daemon - Note that other things such as user permissions may also play a role at this point.

    This brings me to another point - As the standard filehandles are closed as part of the initialisation process of Proc::Daemon, it is necessary to incorporate another means of error reporting, such as the system log or a dedicated application log file, as opposed to reporting errors to STDERR - This step alone should help you determine the cause of the error at hand.

    Update - If the main role at hand is to manipulate a PID file, then the module Proc::PID::File may also be of interest.

      Thank you for the help, I will try this out when I get home tonight.

      A log file was the next thing on my list to do funny enough.

      So is there a way to find out what directory a script is running in? so that I dont have to hard code the path into the script.

      I want people to be able to drop this into a cgi-bin and away they go without having to find out lots of information about their system.
        As far as figuring out what directory you're in, perhaps $pwd=`pwd`;?

        _________________________________________________________________________________

        I like computer programming because it's like Legos for the mind.