-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaster.class.php
More file actions
72 lines (58 loc) · 1.71 KB
/
master.class.php
File metadata and controls
72 lines (58 loc) · 1.71 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
<?php
require_once "daemon.class.php";
abstract class Master extends Daemon
{
protected $children = array();
public function __construct($config_file)
{
parent::__construct($config_file);
}
protected function register_signals()
{
parent::register_signals();
pcntl_signal(SIGCHLD, array(&$this, "reap"));
}
protected function run_cycle()
{
while ($this->config["max_children"] > count($this->children)) {
$pid = pcntl_fork();
if (-1 == $pid) {
$this->log("fork failed!");
}
elseif (0 == $pid) {
$this->open_std_files();
$worker = new $this->config["worker_class"]($this->create_worker_config());
$worker->start();
exit(0);
}
else {
$this->children[$pid] = $pid;
if ($this->config["debug"]) {
$this->log(sprintf("spawned child: %d, total children count: %d", $pid, count($this->children)));
}
}
}
sleep(1); // 1 should be hardcoded because of signal dispatching
}
protected function before_shutdown()
{
$this->terminate_children();
}
protected function after_configure()
{
$this->terminate_children();
}
abstract protected function create_worker_config();
protected function reap()
{
while (0 < $pid = pcntl_waitpid(-1, $status, WNOHANG)) {
unset($this->children[$pid]);
}
}
protected function terminate_children()
{
foreach ($this->children as $pid => $data) {
posix_kill($pid, SIGTERM);
}
}
}