]> git.mxchange.org Git - friendica.git/blob - util/daemon.php
Merge branch 'develop' into utf8mb4
[friendica.git] / util / daemon.php
1 <?php
2 /**
3  * @file util/daemon.php
4  * @brief Run the poller from a daemon.
5  *
6  * This script was taken from http://php.net/manual/en/function.pcntl-fork.php
7  */
8 function shutdown() {
9         posix_kill(posix_getpid(), SIGHUP);
10 }
11
12 if (in_array("start", $_SERVER["argv"])) {
13         $mode = "start";
14 }
15
16 if (in_array("stop", $_SERVER["argv"])) {
17         $mode = "stop";
18 }
19
20 if (in_array("status", $_SERVER["argv"])) {
21         $mode = "status";
22 }
23
24 if (!isset($mode)) {
25         die("Please use either 'start', 'stop' or 'status'.\n");
26 }
27
28 @include(".htconfig.php");
29
30 if (!isset($pidfile)) {
31         die('Please specify a pid file in the variable $pidfile in the .htconfig.php. For example:'."\n".
32                 '$pidfile = "/path/to/daemon.pid";'."\n");
33 }
34
35 if (in_array($mode, array("stop", "status"))) {
36         $pid = @file_get_contents($pidfile);
37
38         if (!$pid) {
39                 die("Pidfile wasn't found. Is the daemon running?\n");
40         }
41 }
42
43 if ($mode == "status") {
44         if (posix_kill($pid, 0)) {
45                 die("Daemon process $pid is running.\n");
46         }
47
48         unlink($pidfile);
49
50         die("Daemon process $pid isn't running.\n");
51 }
52
53 if ($mode == "stop") {
54         posix_kill($pid, SIGTERM);
55
56         unlink($pidfile);
57
58         die("Worker daemon process $pid was killed.\n");
59 }
60
61 echo "Starting worker daemon.\n";
62
63 if (isset($a->config['php_path'])) {
64         $php = $a->config['php_path'];
65 } else {
66         $php = "php";
67 }
68
69 // Switch over to daemon mode.
70 if ($pid = pcntl_fork())
71         return;     // Parent
72
73 fclose(STDIN);  // Close all of the standard
74 fclose(STDOUT); // file descriptors as we
75 fclose(STDERR); // are running as a daemon.
76
77 register_shutdown_function('shutdown');
78
79 if (posix_setsid() < 0)
80         return;
81
82 if ($pid = pcntl_fork())
83         return;     // Parent
84
85 $pid = getmypid();
86 file_put_contents($pidfile, $pid);
87
88 // Now running as a daemon.
89 while (true) {
90         // Just to be sure that this script really runs endlessly
91         set_time_limit(0);
92
93         // Call the poller
94         $cmdline = $php.' include/poller.php';
95
96         exec($cmdline);
97
98         // Now sleep for 5 minutes
99         sleep(300);
100 }
101 ?>