-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaemon.class.php
More file actions
100 lines (80 loc) · 2.38 KB
/
daemon.class.php
File metadata and controls
100 lines (80 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
require_once "worker.class.php";
abstract class Daemon extends Worker
{
protected $config = array(
"daemonize" => true,
"debug" => false,
);
protected $config_file;
protected $_log;
public function __construct($config_file)
{
$this->config_file = $config_file;
$this->running = true;
}
public function start()
{
$this->configure();
$this->detach();
$this->open_std_files();
parent::start();
}
protected function log($message)
{
fwrite($this->_log, sprintf("%s [%d] %s %s\n", strftime("%F %T"), posix_getpid(), get_class($this), $message));
}
protected function shutdown()
{
fclose($this->_log);
if ($this->config["daemonize"]) {
unlink($this->config["pidfile"]);
}
parent::shutdown();
}
protected function register_signals()
{
parent::register_signals();
pcntl_signal(SIGHUP, array(&$this, "configure"));
pcntl_signal(SIGINT, array(&$this, "stop"));
pcntl_signal(SIGUSR1, array(&$this, "open_std_files"));
}
protected function after_configure() { }
protected function after_detach() { }
protected function configure()
{
if ($this->config["debug"]) {
$this->log("configuring");
}
$this->config = array_merge($this->config, yaml_parse_file($this->config_file));
$this->after_configure();
}
protected function detach()
{
if ($this->config["daemonize"]) {
$pid = pcntl_fork();
if (-1 == $pid)
die("fork failed");
elseif (0 < $pid)
exit(0);
if (-1 == posix_setsid())
die("setsid failed");
file_put_contents($this->config["pidfile"], posix_getpid() . "\n");
}
$this->after_detach();
}
protected function open_std_files()
{
if ($this->config["daemonize"]) {
if (is_resource(STDOUT)) fclose(STDOUT);
if (is_resource(STDERR)) fclose(STDERR);
if (is_resource(STDIN)) fclose(STDIN);
fopen("/dev/null", "r");
fopen($this->config["logfile"], "ab");
$this->_log = fopen($this->config["logfile"], "ab");
}
else {
$this->_log = fopen("php://stderr", "ab");
}
}
}