Posts Tagged ‘fork’

Forking Daemons in PHP

Thursday, April 30th, 2009
No Gravatar

Note: this is from http://bipinb.com/making-php-program-as-daemon.htm . It has been intermittently offline, so I’m archiving it here for future reference.


<?php
include_once('createdb.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
 $dbobject = new DB();
 $dbobject->getCon();
 while (1) {
// do something interesting here, here i have called a function from other flile called "createdb.php"
$dbobject->CopyCallFiles();
}
 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
 }
}
?>
  • Share/Bookmark