PHP as Daemon

Posted on July 27th, 2006 in PHP by Russ

I had to write a php script that lived in an endless loop. However, once I started and backgrounded the process, I found that I couldn’t log out. Well, I could “log out” but the terminal session wouldn’t end until my processes quit. So I was stuck onto the server forever.

The solution to this would be to make the service detach from itself and then “run as a daemon.” I took about an hour and looked for examples on the web. The most popular ‘php as daemon’ script (on php.net) was a server that also did some port access and that sort of thing. All I needed was the “daemon”-ness and the pid of the child process. I’m sharing what I learned here- so you can start from my spot.


#!/usr/bin/php -q // adjust this for whereever your php is.
< ?php
$fh=fopen("/tmp/test.log", "a+"); // this is just opening the file to have something to do.

$notforked=pcntl_fork(); // this is the magic part.
$childpid=getmypid(); // this is the part that has the value for the pid file
if ($pid== -1) {
die('aiee!'); // something wrong happened, pcntl_fork didn't get run right. you might need to recompile php
}
elseif ( $notforked ) { // for some reason, we got back a non-zero value from the pcntl_fork() function.
}
else { // we were successfully forked.
while( true ) { // do this forever!
fwrite( $fh, mktime()." $childpid\n" ); // this is just a dorky example of something to do.
sleep(1); // if we don't sleep, the log file gets too big.
} // end of while
}// end of else

There's some other things out there that can be done; you can handle signals (SIG_HUP, SIG_KILL) sent to your process and do some cleanup; but this is the basic "how do I break off to an eternal loop?" solution. I left "save the pid in a pidfile" as an exercise for the reader.

2 Responses to 'PHP as Daemon'

Subscribe to comments with RSS or TrackBack to 'PHP as Daemon'.

  1. Stephen said,

    on August 15th, 2006 at 2:05 pm

    Russ – Man, Ive been trying to solve this issue for days…finding this post was a life saver. One question though, I’m not clear on the elseif statement..can you elaborate on why that has no function or output?

  2. Russ said,

    on August 15th, 2006 at 2:12 pm

    If you take a look at this page:
    http://us2.php.net/manual/en/function.pcntl-fork.php — you’ll get a better idea. It has to do on whether today we’re the child or the parent. I was just being lazy and only addressing what I needed right away.

Leave a comment