On 03/10/2010 08:24 AM, p...@0ne.us wrote:
> Winfried Neessen wrote:
>> Hi,
>>
>>  
>>
>> I've written a server application using POE which is working pretty well
>> now. It's preforking some
>>
>> processes and then listens on a TCP port to acceppt client request.
>>
>>  
>>
>> Now I'd like to run it independently, so my question is, is there an
>> easy way for me to run a POE
>>
>> script daemonized (w/o having to use Unix backgrounding/forking)?
>>  
>>
>> Any hint is greatly appreciated.
>>
>>  
>>
>>  
>>
>> Thanks
>>
>> Winni
>>
>>
>>   
> Hello,
>
>    There are several ways you can accomplish this. I've been using
> Net::Server::Daemonize in $work code to good results. There's other
> modules floating around in the CPAN - all you need to do is a quick
> search of "daemon" and search.cpan.org turns up 123 results!
>
>    However, one "gotcha" about using those daemonize modules is that
> you better wrap it in a BEGIN block so you are daemonized *before* you
> fire up POE or weird things will happen ( in my case heh )
>
> ~Apocalypse
>
>

Below is the code I use.  It's a slightly modified version I found when
I googled for Perl daemon

sub daemonize {

    # check to see if the PID file already exists.
    if ( -f $pid_file ) {

        # there is a PID file.  Check to see if the
        # process with that ID is alive.
        my $rpid = `cat $pid_file`;

        # strip whitespace.
        $rpid =~ s/[\t \n\r]+//g;

        # if there is something useful in the PID file and if we can signal
        # that process, then there is another copy of this routine running.
        if ( $rpid && ( kill 0, $rpid ) ) {

            # the process exists.  Terminate with an error.
            print STDERR "ERROR: $0 daemon process already running with
PID $rpid! Exiting...\n";
            error( "$0 daemon process already running with PID $rpid!
Exiting...");
            exit(1);
        }
    }

    chdir '/' or die "Can't chdir to /: $!";
    open STDIN,  '/dev/null'  or die "Can't read /dev/null: $!";
    open STDOUT, '>/dev/null' or die "Can't write to /dev/null: $!";
    defined( my $pid = fork ) or die "Can't fork: $!";
    exit if $pid;
    setsid or die "Can't start a new session: $!";

    # open STDERR, ">&$log_fh" or die "Can't dup logfile: $!";
    print STDERR "$0: New pid is $$\n";
    open STDERR, ">& STDOUT" or die "Can't dup logfile: $!";
    if ( !open( PF, ">$pid_file" ) ) {
       
        my $msg = "Could not open PID file '$pid_file': $!";
        error($msg);
       
        die "ERROR: $msg";
    }
    print PF "$$\n";
    close(PF);
    info("$0 has been spawned with a pid of $$\n");
}

Reply via email to