| 1 |
<?php |
| 2 |
|
| 3 |
namespace React\ChildProcess; |
| 4 |
|
| 5 |
use Evenement\EventEmitter; |
| 6 |
use React\EventLoop\LoopInterface; |
| 7 |
use React\Stream\ReadableResourceStream; |
| 8 |
use React\Stream\ReadableStreamInterface; |
| 9 |
use React\Stream\WritableResourceStream; |
| 10 |
use React\Stream\WritableStreamInterface; |
| 11 |
use React\Stream\DuplexResourceStream; |
| 12 |
use React\Stream\DuplexStreamInterface; |
| 13 |
|
| 14 |
/** |
| 15 |
* Process component. |
| 16 |
* |
| 17 |
* This class borrows logic from Symfony's Process component for ensuring |
| 18 |
* compatibility when PHP is compiled with the --enable-sigchild option. |
| 19 |
* |
| 20 |
* This class also implements the `EventEmitterInterface` |
| 21 |
* which allows you to react to certain events: |
| 22 |
* |
| 23 |
* exit event: |
| 24 |
* The `exit` event will be emitted whenever the process is no longer running. |
| 25 |
* Event listeners will receive the exit code and termination signal as two |
| 26 |
* arguments: |
| 27 |
* |
| 28 |
* ```php |
| 29 |
* $process = new Process('sleep 10'); |
| 30 |
* $process->start($loop); |
| 31 |
* |
| 32 |
* $process->on('exit', function ($code, $term) { |
| 33 |
* if ($term === null) { |
| 34 |
* echo 'exit with code ' . $code . PHP_EOL; |
| 35 |
* } else { |
| 36 |
* echo 'terminated with signal ' . $term . PHP_EOL; |
| 37 |
* } |
| 38 |
* }); |
| 39 |
* ``` |
| 40 |
* |
| 41 |
* Note that `$code` is `null` if the process has terminated, but the exit |
| 42 |
* code could not be determined (for example |
| 43 |
* [sigchild compatibility](#sigchild-compatibility) was disabled). |
| 44 |
* Similarly, `$term` is `null` unless the process has terminated in response to |
| 45 |
* an uncaught signal sent to it. |
| 46 |
* This is not a limitation of this project, but actual how exit codes and signals |
| 47 |
* are exposed on POSIX systems, for more details see also |
| 48 |
* [here](https://unix.stackexchange.com/questions/99112/default-exit-code-when-process-is-terminated). |
| 49 |
* |
| 50 |
* It's also worth noting that process termination depends on all file descriptors |
| 51 |
* being closed beforehand. |
| 52 |
* This means that all [process pipes](#stream-properties) will emit a `close` |
| 53 |
* event before the `exit` event and that no more `data` events will arrive after |
| 54 |
* the `exit` event. |
| 55 |
* Accordingly, if either of these pipes is in a paused state (`pause()` method |
| 56 |
* or internally due to a `pipe()` call), this detection may not trigger. |
| 57 |
*/ |
| 58 |
class Process extends EventEmitter |
| 59 |
{ |
| 60 |
/** |
| 61 |
* @var WritableStreamInterface|null|DuplexStreamInterface|ReadableStreamInterface |
| 62 |
*/ |
| 63 |
public $stdin; |
| 64 |
|
| 65 |
/** |
| 66 |
* @var ReadableStreamInterface|null|DuplexStreamInterface|WritableStreamInterface |
| 67 |
*/ |
| 68 |
public $stdout; |
| 69 |
|
| 70 |
/** |
| 71 |
* @var ReadableStreamInterface|null|DuplexStreamInterface|WritableStreamInterface |
| 72 |
*/ |
| 73 |
public $stderr; |
| 74 |
|
| 75 |
/** |
| 76 |
* Array with all process pipes (once started) |
| 77 |
* |
| 78 |
* Unless explicitly configured otherwise during construction, the following |
| 79 |
* standard I/O pipes will be assigned by default: |
| 80 |
* - 0: STDIN (`WritableStreamInterface`) |
| 81 |
* - 1: STDOUT (`ReadableStreamInterface`) |
| 82 |
* - 2: STDERR (`ReadableStreamInterface`) |
| 83 |
* |
| 84 |
* @var array<ReadableStreamInterface|WritableStreamInterface|DuplexStreamInterface> |
| 85 |
*/ |
| 86 |
public $pipes = array(); |
| 87 |
|
| 88 |
private $cmd; |
| 89 |
private $cwd; |
| 90 |
private $env; |
| 91 |
private $fds; |
| 92 |
|
| 93 |
private $enhanceSigchildCompatibility; |
| 94 |
private $sigchildPipe; |
| 95 |
|
| 96 |
private $process; |
| 97 |
private $status; |
| 98 |
private $exitCode; |
| 99 |
private $fallbackExitCode; |
| 100 |
private $stopSignal; |
| 101 |
private $termSignal; |
| 102 |
|
| 103 |
private static $sigchild; |
| 104 |
|
| 105 |
/** |
| 106 |
* Constructor. |
| 107 |
* |
| 108 |
* @param string $cmd Command line to run |
| 109 |
* @param null|string $cwd Current working directory or null to inherit |
| 110 |
* @param null|array $env Environment variables or null to inherit |
| 111 |
* @param null|array $fds File descriptors to allocate for this process (or null = default STDIO streams) |
| 112 |
* @throws \LogicException On windows or when proc_open() is not installed |
| 113 |
*/ |
| 114 |
public function __construct($cmd, $cwd = null, array $env = null, array $fds = null) |
| 115 |
{ |
| 116 |
if (!\function_exists('proc_open')) { |
| 117 |
throw new \LogicException('The Process class relies on proc_open(), which is not available on your PHP installation.'); |
| 118 |
} |
| 119 |
|
| 120 |
$this->cmd = $cmd; |
| 121 |
$this->cwd = $cwd; |
| 122 |
|
| 123 |
if (null !== $env) { |
| 124 |
$this->env = array(); |
| 125 |
foreach ($env as $key => $value) { |
| 126 |
$this->env[(binary) $key] = (binary) $value; |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
if ($fds === null) { |
| 131 |
$fds = array( |
| 132 |
array('pipe', 'r'), // stdin |
| 133 |
array('pipe', 'w'), // stdout |
| 134 |
array('pipe', 'w'), // stderr |
| 135 |
); |
| 136 |
} |
| 137 |
|
| 138 |
if (\DIRECTORY_SEPARATOR === '\\') { |
| 139 |
foreach ($fds as $fd) { |
| 140 |
if (isset($fd[0]) && $fd[0] === 'pipe') { |
| 141 |
throw new \LogicException('Process pipes are not supported on Windows due to their blocking nature on Windows'); |
| 142 |
} |
| 143 |
} |
| 144 |
} |
| 145 |
|
| 146 |
$this->fds = $fds; |
| 147 |
$this->enhanceSigchildCompatibility = self::isSigchildEnabled(); |
| 148 |
} |
| 149 |
|
| 150 |
/** |
| 151 |
* Start the process. |
| 152 |
* |
| 153 |
* After the process is started, the standard I/O streams will be constructed |
| 154 |
* and available via public properties. |
| 155 |
* |
| 156 |
* @param LoopInterface $loop Loop interface for stream construction |
| 157 |
* @param float $interval Interval to periodically monitor process state (seconds) |
| 158 |
* @throws \RuntimeException If the process is already running or fails to start |
| 159 |
*/ |
| 160 |
public function start(LoopInterface $loop, $interval = 0.1) |
| 161 |
{ |
| 162 |
if ($this->isRunning()) { |
| 163 |
throw new \RuntimeException('Process is already running'); |
| 164 |
} |
| 165 |
|
| 166 |
$cmd = $this->cmd; |
| 167 |
$fdSpec = $this->fds; |
| 168 |
$sigchild = null; |
| 169 |
|
| 170 |
// Read exit code through fourth pipe to work around --enable-sigchild |
| 171 |
if ($this->enhanceSigchildCompatibility) { |
| 172 |
$fdSpec[] = array('pipe', 'w'); |
| 173 |
\end($fdSpec); |
| 174 |
$sigchild = \key($fdSpec); |
| 175 |
|
| 176 |
// make sure this is fourth or higher (do not mess with STDIO) |
| 177 |
if ($sigchild < 3) { |
| 178 |
$fdSpec[3] = $fdSpec[$sigchild]; |
| 179 |
unset($fdSpec[$sigchild]); |
| 180 |
$sigchild = 3; |
| 181 |
} |
| 182 |
|
| 183 |
$cmd = \sprintf('(%s) ' . $sigchild . '>/dev/null; code=$?; echo $code >&' . $sigchild . '; exit $code', $cmd); |
| 184 |
} |
| 185 |
|
| 186 |
// on Windows, we do not launch the given command line in a shell (cmd.exe) by default and omit any error dialogs |
| 187 |
// the cmd.exe shell can explicitly be given as part of the command as detailed in both documentation and tests |
| 188 |
$options = array(); |
| 189 |
if (\DIRECTORY_SEPARATOR === '\\') { |
| 190 |
$options['bypass_shell'] = true; |
| 191 |
$options['suppress_errors'] = true; |
| 192 |
} |
| 193 |
|
| 194 |
$this->process = @\proc_open($cmd, $fdSpec, $pipes, $this->cwd, $this->env, $options); |
| 195 |
|
| 196 |
if (!\is_resource($this->process)) { |
| 197 |
$error = \error_get_last(); |
| 198 |
throw new \RuntimeException('Unable to launch a new process: ' . $error['message']); |
| 199 |
} |
| 200 |
|
| 201 |
// count open process pipes and await close event for each to drain buffers before detecting exit |
| 202 |
$that = $this; |
| 203 |
$closeCount = 0; |
| 204 |
$streamCloseHandler = function () use (&$closeCount, $loop, $interval, $that) { |
| 205 |
$closeCount--; |
| 206 |
|
| 207 |
if ($closeCount > 0) { |
| 208 |
return; |
| 209 |
} |
| 210 |
|
| 211 |
// process already closed => report immediately |
| 212 |
if (!$that->isRunning()) { |
| 213 |
$that->close(); |
| 214 |
$that->emit('exit', array($that->getExitCode(), $that->getTermSignal())); |
| 215 |
return; |
| 216 |
} |
| 217 |
|
| 218 |
// close not detected immediately => check regularly |
| 219 |
$loop->addPeriodicTimer($interval, function ($timer) use ($that, $loop) { |
| 220 |
if (!$that->isRunning()) { |
| 221 |
$loop->cancelTimer($timer); |
| 222 |
$that->close(); |
| 223 |
$that->emit('exit', array($that->getExitCode(), $that->getTermSignal())); |
| 224 |
} |
| 225 |
}); |
| 226 |
}; |
| 227 |
|
| 228 |
if ($sigchild !== null) { |
| 229 |
$this->sigchildPipe = $pipes[$sigchild]; |
| 230 |
unset($pipes[$sigchild]); |
| 231 |
} |
| 232 |
|
| 233 |
foreach ($pipes as $n => $fd) { |
| 234 |
// use open mode from stream meta data or fall back to pipe open mode for legacy HHVM |
| 235 |
$meta = \stream_get_meta_data($fd); |
| 236 |
$mode = $meta['mode'] === '' ? ($this->fds[$n][1] === 'r' ? 'w' : 'r') : $meta['mode']; |
| 237 |
|
| 238 |
if ($mode === 'r+') { |
| 239 |
$stream = new DuplexResourceStream($fd, $loop); |
| 240 |
} elseif ($mode === 'w') { |
| 241 |
$stream = new WritableResourceStream($fd, $loop); |
| 242 |
} else { |
| 243 |
$stream = new ReadableResourceStream($fd, $loop); |
| 244 |
$stream->on('close', $streamCloseHandler); |
| 245 |
$closeCount++; |
| 246 |
} |
| 247 |
$this->pipes[$n] = $stream; |
| 248 |
} |
| 249 |
|
| 250 |
$this->stdin = isset($this->pipes[0]) ? $this->pipes[0] : null; |
| 251 |
$this->stdout = isset($this->pipes[1]) ? $this->pipes[1] : null; |
| 252 |
$this->stderr = isset($this->pipes[2]) ? $this->pipes[2] : null; |
| 253 |
|
| 254 |
// immediately start checking for process exit when started without any I/O pipes |
| 255 |
if (!$closeCount) { |
| 256 |
$streamCloseHandler(); |
| 257 |
} |
| 258 |
} |
| 259 |
|
| 260 |
/** |
| 261 |
* Close the process. |
| 262 |
* |
| 263 |
* This method should only be invoked via the periodic timer that monitors |
| 264 |
* the process state. |
| 265 |
*/ |
| 266 |
public function close() |
| 267 |
{ |
| 268 |
if ($this->process === null) { |
| 269 |
return; |
| 270 |
} |
| 271 |
|
| 272 |
foreach ($this->pipes as $pipe) { |
| 273 |
$pipe->close(); |
| 274 |
} |
| 275 |
|
| 276 |
if ($this->enhanceSigchildCompatibility) { |
| 277 |
$this->pollExitCodePipe(); |
| 278 |
$this->closeExitCodePipe(); |
| 279 |
} |
| 280 |
|
| 281 |
$exitCode = \proc_close($this->process); |
| 282 |
$this->process = null; |
| 283 |
|
| 284 |
if ($this->exitCode === null && $exitCode !== -1) { |
| 285 |
$this->exitCode = $exitCode; |
| 286 |
} |
| 287 |
|
| 288 |
if ($this->exitCode === null && $this->status['exitcode'] !== -1) { |
| 289 |
$this->exitCode = $this->status['exitcode']; |
| 290 |
} |
| 291 |
|
| 292 |
if ($this->exitCode === null && $this->fallbackExitCode !== null) { |
| 293 |
$this->exitCode = $this->fallbackExitCode; |
| 294 |
$this->fallbackExitCode = null; |
| 295 |
} |
| 296 |
} |
| 297 |
|
| 298 |
/** |
| 299 |
* Terminate the process with an optional signal. |
| 300 |
* |
| 301 |
* @param int $signal Optional signal (default: SIGTERM) |
| 302 |
* @return bool Whether the signal was sent successfully |
| 303 |
*/ |
| 304 |
public function terminate($signal = null) |
| 305 |
{ |
| 306 |
if ($this->process === null) { |
| 307 |
return false; |
| 308 |
} |
| 309 |
|
| 310 |
if ($signal !== null) { |
| 311 |
return \proc_terminate($this->process, $signal); |
| 312 |
} |
| 313 |
|
| 314 |
return \proc_terminate($this->process); |
| 315 |
} |
| 316 |
|
| 317 |
/** |
| 318 |
* Get the command string used to launch the process. |
| 319 |
* |
| 320 |
* @return string |
| 321 |
*/ |
| 322 |
public function getCommand() |
| 323 |
{ |
| 324 |
return $this->cmd; |
| 325 |
} |
| 326 |
|
| 327 |
/** |
| 328 |
* Get the exit code returned by the process. |
| 329 |
* |
| 330 |
* This value is only meaningful if isRunning() has returned false. Null |
| 331 |
* will be returned if the process is still running. |
| 332 |
* |
| 333 |
* Null may also be returned if the process has terminated, but the exit |
| 334 |
* code could not be determined (e.g. sigchild compatibility was disabled). |
| 335 |
* |
| 336 |
* @return int|null |
| 337 |
*/ |
| 338 |
public function getExitCode() |
| 339 |
{ |
| 340 |
return $this->exitCode; |
| 341 |
} |
| 342 |
|
| 343 |
/** |
| 344 |
* Get the process ID. |
| 345 |
* |
| 346 |
* @return int|null |
| 347 |
*/ |
| 348 |
public function getPid() |
| 349 |
{ |
| 350 |
$status = $this->getCachedStatus(); |
| 351 |
|
| 352 |
return $status !== null ? $status['pid'] : null; |
| 353 |
} |
| 354 |
|
| 355 |
/** |
| 356 |
* Get the signal that caused the process to stop its execution. |
| 357 |
* |
| 358 |
* This value is only meaningful if isStopped() has returned true. Null will |
| 359 |
* be returned if the process was never stopped. |
| 360 |
* |
| 361 |
* @return int|null |
| 362 |
*/ |
| 363 |
public function getStopSignal() |
| 364 |
{ |
| 365 |
return $this->stopSignal; |
| 366 |
} |
| 367 |
|
| 368 |
/** |
| 369 |
* Get the signal that caused the process to terminate its execution. |
| 370 |
* |
| 371 |
* This value is only meaningful if isTerminated() has returned true. Null |
| 372 |
* will be returned if the process was never terminated. |
| 373 |
* |
| 374 |
* @return int|null |
| 375 |
*/ |
| 376 |
public function getTermSignal() |
| 377 |
{ |
| 378 |
return $this->termSignal; |
| 379 |
} |
| 380 |
|
| 381 |
/** |
| 382 |
* Return whether the process is still running. |
| 383 |
* |
| 384 |
* @return bool |
| 385 |
*/ |
| 386 |
public function isRunning() |
| 387 |
{ |
| 388 |
if ($this->process === null) { |
| 389 |
return false; |
| 390 |
} |
| 391 |
|
| 392 |
$status = $this->getFreshStatus(); |
| 393 |
|
| 394 |
return $status !== null ? $status['running'] : false; |
| 395 |
} |
| 396 |
|
| 397 |
/** |
| 398 |
* Return whether the process has been stopped by a signal. |
| 399 |
* |
| 400 |
* @return bool |
| 401 |
*/ |
| 402 |
public function isStopped() |
| 403 |
{ |
| 404 |
$status = $this->getFreshStatus(); |
| 405 |
|
| 406 |
return $status !== null ? $status['stopped'] : false; |
| 407 |
} |
| 408 |
|
| 409 |
/** |
| 410 |
* Return whether the process has been terminated by an uncaught signal. |
| 411 |
* |
| 412 |
* @return bool |
| 413 |
*/ |
| 414 |
public function isTerminated() |
| 415 |
{ |
| 416 |
$status = $this->getFreshStatus(); |
| 417 |
|
| 418 |
return $status !== null ? $status['signaled'] : false; |
| 419 |
} |
| 420 |
|
| 421 |
/** |
| 422 |
* Return whether PHP has been compiled with the '--enable-sigchild' option. |
| 423 |
* |
| 424 |
* @see \Symfony\Component\Process\Process::isSigchildEnabled() |
| 425 |
* @return bool |
| 426 |
*/ |
| 427 |
public final static function isSigchildEnabled() |
| 428 |
{ |
| 429 |
if (null !== self::$sigchild) { |
| 430 |
return self::$sigchild; |
| 431 |
} |
| 432 |
|
| 433 |
\ob_start(); |
| 434 |
\phpinfo(INFO_GENERAL); |
| 435 |
|
| 436 |
return self::$sigchild = false !== \strpos(\ob_get_clean(), '--enable-sigchild'); |
| 437 |
} |
| 438 |
|
| 439 |
/** |
| 440 |
* Enable or disable sigchild compatibility mode. |
| 441 |
* |
| 442 |
* Sigchild compatibility mode is required to get the exit code and |
| 443 |
* determine the success of a process when PHP has been compiled with |
| 444 |
* the --enable-sigchild option. |
| 445 |
* |
| 446 |
* @param bool $sigchild |
| 447 |
* @return void |
| 448 |
*/ |
| 449 |
public final static function setSigchildEnabled($sigchild) |
| 450 |
{ |
| 451 |
self::$sigchild = (bool) $sigchild; |
| 452 |
} |
| 453 |
|
| 454 |
/** |
| 455 |
* Check the fourth pipe for an exit code. |
| 456 |
* |
| 457 |
* This should only be used if --enable-sigchild compatibility was enabled. |
| 458 |
*/ |
| 459 |
private function pollExitCodePipe() |
| 460 |
{ |
| 461 |
if ($this->sigchildPipe === null) { |
| 462 |
return; |
| 463 |
} |
| 464 |
|
| 465 |
$r = array($this->sigchildPipe); |
| 466 |
$w = $e = null; |
| 467 |
|
| 468 |
$n = @\stream_select($r, $w, $e, 0); |
| 469 |
|
| 470 |
if (1 !== $n) { |
| 471 |
return; |
| 472 |
} |
| 473 |
|
| 474 |
$data = \fread($r[0], 8192); |
| 475 |
|
| 476 |
if (\strlen($data) > 0) { |
| 477 |
$this->fallbackExitCode = (int) $data; |
| 478 |
} |
| 479 |
} |
| 480 |
|
| 481 |
/** |
| 482 |
* Close the fourth pipe used to relay an exit code. |
| 483 |
* |
| 484 |
* This should only be used if --enable-sigchild compatibility was enabled. |
| 485 |
*/ |
| 486 |
private function closeExitCodePipe() |
| 487 |
{ |
| 488 |
if ($this->sigchildPipe === null) { |
| 489 |
return; |
| 490 |
} |
| 491 |
|
| 492 |
\fclose($this->sigchildPipe); |
| 493 |
$this->sigchildPipe = null; |
| 494 |
} |
| 495 |
|
| 496 |
/** |
| 497 |
* Return the cached process status. |
| 498 |
* |
| 499 |
* @return array |
| 500 |
*/ |
| 501 |
private function getCachedStatus() |
| 502 |
{ |
| 503 |
if ($this->status === null) { |
| 504 |
$this->updateStatus(); |
| 505 |
} |
| 506 |
|
| 507 |
return $this->status; |
| 508 |
} |
| 509 |
|
| 510 |
/** |
| 511 |
* Return the updated process status. |
| 512 |
* |
| 513 |
* @return array |
| 514 |
*/ |
| 515 |
private function getFreshStatus() |
| 516 |
{ |
| 517 |
$this->updateStatus(); |
| 518 |
|
| 519 |
return $this->status; |
| 520 |
} |
| 521 |
|
| 522 |
/** |
| 523 |
* Update the process status, stop/term signals, and exit code. |
| 524 |
* |
| 525 |
* Stop/term signals are only updated if the process is currently stopped or |
| 526 |
* signaled, respectively. Otherwise, signal values will remain as-is so the |
| 527 |
* corresponding getter methods may be used at a later point in time. |
| 528 |
*/ |
| 529 |
private function updateStatus() |
| 530 |
{ |
| 531 |
if ($this->process === null) { |
| 532 |
return; |
| 533 |
} |
| 534 |
|
| 535 |
$this->status = \proc_get_status($this->process); |
| 536 |
|
| 537 |
if ($this->status === false) { |
| 538 |
throw new \UnexpectedValueException('proc_get_status() failed'); |
| 539 |
} |
| 540 |
|
| 541 |
if ($this->status['stopped']) { |
| 542 |
$this->stopSignal = $this->status['stopsig']; |
| 543 |
} |
| 544 |
|
| 545 |
if ($this->status['signaled']) { |
| 546 |
$this->termSignal = $this->status['termsig']; |
| 547 |
} |
| 548 |
|
| 549 |
if (!$this->status['running'] && -1 !== $this->status['exitcode']) { |
| 550 |
$this->exitCode = $this->status['exitcode']; |
| 551 |
} |
| 552 |
} |
| 553 |
} |