I needed to run a PHP script in the background on my Ubuntu 8.04 server, but didn’t know how to do this. Googling around I found the following script to daemonize PHP scripts on bipinb.com:
<?php
declare(ticks=1);
$pid = pcntl_fork();
if ($pid == -1) {
die("could not fork");
} else
if ($pid) {
exit();
// we are the parent
} else {
// we are the child
}
// detatch from the controlling terminal
if (posix_setsid() == -1) {
die("could not detach from terminal");
}
$posid=posix_getpid();
$fp = fopen("/var/run/process.pid", "w");
fwrite($fp, $posid);
fclose($fp);
// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
// loop forever performing tasks
// **** place your main PHP code here ****
while (1) {
// **** place the PHP code that loops in here ****
}
fclose($fp);
function sig_handler($signo) {
switch ($signo) {
case SIGTERM:
// handle shutdown tasks
exit;
break;
case SIGHUP:
// handle restart tasks
break;
default:
// handle all other signals
}
}
?>
I inserted my code and ran the script from the console. It all looked good, but found that whenever I left the console, the script would stop.
After some more googling I ended up on kevin.vanzonneveld.net, where I found a lot of information on creating daemons in PHP. In the troubleshooting area I found the following:
Don’t use echo()
Echo writes to the STDOUT of your current session. If you logout, that will cause fatal errors and the daemon to die. Use System_Daemon::log() instead.
This was the problem… in my PHP code I had some echo statements. When I deleted them, my PHP daemon was (and stayed) alive!