Skip to content

Commit 877aed9

Browse files
committed
pcntl_wait 有可能在捕获所有子进程推出之前,提前返回 -1
1 parent 4d3a380 commit 877aed9

File tree

1 file changed

+13
-12
lines changed

1 file changed

+13
-12
lines changed

src/Process.php

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ class Process
2929

3030
protected static $workers = [];
3131

32+
protected static $shutdown = false;
33+
3234
public function setJob(callable $job)
3335
{
3436
$this->job = $job;
@@ -130,7 +132,8 @@ protected function redirectStd()
130132

131133
protected function waitAll()
132134
{
133-
while (($pid = pcntl_wait($status, WUNTRACED)) != -1) {
135+
while (1) {
136+
$pid = pcntl_wait($status, WUNTRACED);
134137
if ($pid > 0) {
135138
$id = array_search($pid, static::$workers);
136139
if ($id === false) {
@@ -139,11 +142,15 @@ protected function waitAll()
139142
$this->log("[worker:$id $pid] process stopped with status $status");
140143
unset(static::$workers[$id]);
141144

142-
// refork
143-
if ($this->refork) {
145+
if (!static::$shutdown && $this->refork) {
146+
// refork
144147
$this->forkWorker($id);
145148
}
146149
}
150+
151+
if (static::$shutdown && empty(static::$workers)) {
152+
break;
153+
}
147154
}
148155
}
149156

@@ -186,7 +193,8 @@ public function handleShutdown()
186193

187194
public function log($contents)
188195
{
189-
$contents = sprintf("[%s] [master %s] %s\n", date('Y-m-d H:i:s'), $this->masterPid, $contents);
196+
$time = gettimeofday();
197+
$contents = sprintf("[%s.%s] [master %s] %s\n", date('Y-m-d H:i:s', $time['sec']), $time['usec'], $this->masterPid, $contents);
190198
if (!$this->daemonize) {
191199
echo $contents;
192200
}
@@ -224,20 +232,13 @@ public function signalShutdownHandler($signo)
224232
};
225233

226234
if (static::$isMaster) {
235+
static::$shutdown = true;
227236
$this->log($msg);
228237

229238
// Send stop signal to all worker processes.
230239
foreach (static::$workers as $id => $workerPid) {
231240
posix_kill($workerPid, $signo);
232241
}
233-
234-
sleep(1);
235-
foreach (static::$workers as $id => $workerPid) {
236-
if (posix_kill($workerPid, 0)) {
237-
posix_kill($workerPid, SIGKILL);
238-
}
239-
unset(static::$workers[$id]);
240-
}
241242
} else {
242243
$this->log("[worker:{$this->id} {$this->workerPid}] " . $msg);
243244

0 commit comments

Comments
 (0)