PHP as Daemon
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.
