1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Pageon\Pcntl; |
4
|
|
|
|
5
|
|
|
use Brendt\Stitcher\Event\Event; |
6
|
|
|
use Symfony\Component\EventDispatcher\EventDispatcher; |
7
|
|
|
|
8
|
|
|
class Manager |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var EventDispatcher |
12
|
|
|
*/ |
13
|
|
|
private $eventDispatcher; |
14
|
|
|
|
15
|
|
|
public function __construct(EventDispatcher $eventDispatcher) { |
16
|
|
|
$this->eventDispatcher = $eventDispatcher; |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
public function async(Process $process) { |
20
|
|
|
socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets); |
21
|
|
|
|
22
|
|
|
list($parentSocket, $childSocket) = $sockets; |
23
|
|
|
|
24
|
|
|
if (($pid = pcntl_fork()) == 0) { |
25
|
|
|
socket_close($childSocket); |
26
|
|
|
$output = serialize($process->execute()); |
27
|
|
|
socket_write($parentSocket, $output); |
28
|
|
|
socket_close($parentSocket); |
29
|
|
|
|
30
|
|
|
exit; |
|
|
|
|
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
socket_close($parentSocket); |
34
|
|
|
|
35
|
|
|
return new ThreadHandler($pid, $childSocket); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function wait(ThreadHandlerCollection $threadHandlerCollection) { |
39
|
|
|
$output = []; |
40
|
|
|
|
41
|
|
|
/** @var ThreadHandler $threadHandler */ |
42
|
|
|
foreach ($threadHandlerCollection as $threadHandler) { |
43
|
|
|
while (pcntl_waitpid($threadHandler->getPid(), $status) != -1) { |
44
|
|
|
$status = pcntl_wexitstatus($status); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$output = unserialize(socket_read($threadHandler->getSocket(), 4096)); |
48
|
|
|
|
49
|
|
|
if ($output instanceof Event) { |
50
|
|
|
$this->eventDispatcher->dispatch($output->getEventHook(), $output); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
socket_close($threadHandler->getSocket()); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return $output; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
An exit expression should only be used in rare cases. For example, if you write a short command line script.
In most cases however, using an
exit
expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.