-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathForkProcess.php
107 lines (88 loc) · 2.3 KB
/
ForkProcess.php
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
101
102
103
104
105
106
107
<?php
declare(strict_types=1);
namespace axios\tools;
use axios\tools\traits\InstanceTrait;
class ForkProcess
{
use InstanceTrait;
private array $work_queue = [];
private ?int $max_process;
public function __construct($max_process = 100)
{
$this->max_process = $max_process;
$check_funcs = [
'pcntl_fork',
'posix_kill',
'ftok',
'shmop_open',
];
foreach ($check_funcs as $func) {
if (\function_exists($func)) {
continue;
}
throw new \ErrorException($func . '() function is undefined.');
}
}
public function maxProcess($max_process = null): ?int
{
if (null === $max_process) {
$this->max_process = $max_process;
}
return $this->max_process;
}
public function addWork($class, $func, $args = []): self
{
$queue = [
'class' => $class,
'func' => $func,
'args' => $args,
];
$this->work_queue[] = $queue;
return $this;
}
public function run()
{
foreach ($this->work_queue as $q) {
do {
$pid_size = shell_exec('ps -fe |grep "php-fpm"|grep "pool"|wc -l');
} while ($pid_size >= $this->max_process);
$this->exec($q);
}
}
private function exec($queue): bool
{
$class = $queue['class'];
$func = $queue['func'];
$args = $queue['args'];
if (\is_string($class) && class_exists($class)) {
$class = new $class();
}
$fork = $this->fork();
if ($fork) {
return true;
}
\call_user_func_array([$class, $func], $args);
posix_kill(posix_getpid(), \SIGINT);
exit();
}
private function fork(): bool
{
$pid = pcntl_fork();
if ($pid > 0) {
pcntl_wait($status);
return true;
}
if (0 === $pid) {
$ppid = pcntl_fork();
if ($ppid > 0) {
posix_kill(posix_getpid(), \SIGINT);
exit();
}
if (-1 == $ppid) {
exit();
}
return false;
}
return false;
}
}