4 * @file scripts/daemon.php
5 * @brief Run the worker from a daemon.
7 * This script was taken from http://php.net/manual/en/function.pcntl-fork.php
10 posix_kill(posix_getpid(), SIGHUP);
13 if (in_array("start", $_SERVER["argv"])) {
17 if (in_array("stop", $_SERVER["argv"])) {
21 if (in_array("status", $_SERVER["argv"])) {
26 die("Please use either 'start', 'stop' or 'status'.\n");
29 if (empty($_SERVER["argv"][0])) {
30 die("Unexpected script behaviour. This message should never occur.\n");
33 // Fetch the base directory
34 $directory = dirname($_SERVER["argv"][0]);
36 if (substr($directory, 0, 1) != "/") {
37 $directory = $_SERVER["PWD"]."/".$directory;
39 $directory = realpath($directory."/..");
41 @include($directory."/.htconfig.php");
43 if (!isset($pidfile)) {
44 die('Please specify a pid file in the variable $pidfile in the .htconfig.php. For example:'."\n".
45 '$pidfile = "/path/to/daemon.pid";'."\n");
48 if (in_array($mode, array("stop", "status"))) {
49 $pid = @file_get_contents($pidfile);
52 die("Pidfile wasn't found. Is the daemon running?\n");
56 if ($mode == "status") {
57 if (posix_kill($pid, 0)) {
58 die("Daemon process $pid is running.\n");
63 die("Daemon process $pid isn't running.\n");
66 if ($mode == "stop") {
67 posix_kill($pid, SIGTERM);
71 die("Worker daemon process $pid was killed.\n");
74 echo "Starting worker daemon.\n";
76 if (isset($a->config['php_path'])) {
77 $php = $a->config['php_path'];
82 // Switch over to daemon mode.
83 if ($pid = pcntl_fork())
86 fclose(STDIN); // Close all of the standard
87 fclose(STDOUT); // file descriptors as we
88 fclose(STDERR); // are running as a daemon.
90 register_shutdown_function('shutdown');
92 if (posix_setsid() < 0)
95 if ($pid = pcntl_fork())
99 file_put_contents($pidfile, $pid);
101 // Now running as a daemon.
103 // Just to be sure that this script really runs endlessly
107 $cmdline = $php.' scripts/worker.php';
111 if (function_exists('proc_open')) {
112 $resource = proc_open($cmdline . ' &', array(), $foo, $directory);
114 if (is_resource($resource)) {
116 proc_close($resource);
121 exec($cmdline.' spawn');
124 // Now sleep for 5 minutes