Просмотр файла vendor/symfony/process/Process.php

Размер файла: 48.33Kb
  1. <?php
  2.  
  3. /*
  4. * This file is part of the Symfony package.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11.  
  12. namespace Symfony\Component\Process;
  13.  
  14. use Symfony\Component\Process\Exception\InvalidArgumentException;
  15. use Symfony\Component\Process\Exception\LogicException;
  16. use Symfony\Component\Process\Exception\ProcessFailedException;
  17. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  18. use Symfony\Component\Process\Exception\RuntimeException;
  19. use Symfony\Component\Process\Pipes\PipesInterface;
  20. use Symfony\Component\Process\Pipes\UnixPipes;
  21. use Symfony\Component\Process\Pipes\WindowsPipes;
  22.  
  23. /**
  24. * Process is a thin wrapper around proc_* functions to easily
  25. * start independent PHP processes.
  26. *
  27. * @author Fabien Potencier <fabien@symfony.com>
  28. * @author Romain Neutron <imprec@gmail.com>
  29. */
  30. class Process implements \IteratorAggregate
  31. {
  32. const ERR = 'err';
  33. const OUT = 'out';
  34.  
  35. const STATUS_READY = 'ready';
  36. const STATUS_STARTED = 'started';
  37. const STATUS_TERMINATED = 'terminated';
  38.  
  39. const STDIN = 0;
  40. const STDOUT = 1;
  41. const STDERR = 2;
  42.  
  43. // Timeout Precision in seconds.
  44. const TIMEOUT_PRECISION = 0.2;
  45.  
  46. const ITER_NON_BLOCKING = 1; // By default, iterating over outputs is a blocking call, use this flag to make it non-blocking
  47. const ITER_KEEP_OUTPUT = 2; // By default, outputs are cleared while iterating, use this flag to keep them in memory
  48. const ITER_SKIP_OUT = 4; // Use this flag to skip STDOUT while iterating
  49. const ITER_SKIP_ERR = 8; // Use this flag to skip STDERR while iterating
  50.  
  51. private $callback;
  52. private $hasCallback = false;
  53. private $commandline;
  54. private $cwd;
  55. private $env;
  56. private $input;
  57. private $starttime;
  58. private $lastOutputTime;
  59. private $timeout;
  60. private $idleTimeout;
  61. private $options;
  62. private $exitcode;
  63. private $fallbackStatus = array();
  64. private $processInformation;
  65. private $outputDisabled = false;
  66. private $stdout;
  67. private $stderr;
  68. private $enhanceWindowsCompatibility = true;
  69. private $enhanceSigchildCompatibility;
  70. private $process;
  71. private $status = self::STATUS_READY;
  72. private $incrementalOutputOffset = 0;
  73. private $incrementalErrorOutputOffset = 0;
  74. private $tty;
  75. private $pty;
  76. private $inheritEnv = false;
  77.  
  78. private $useFileHandles = false;
  79. /** @var PipesInterface */
  80. private $processPipes;
  81.  
  82. private $latestSignal;
  83.  
  84. private static $sigchild;
  85.  
  86. /**
  87. * Exit codes translation table.
  88. *
  89. * User-defined errors must use exit codes in the 64-113 range.
  90. *
  91. * @var array
  92. */
  93. public static $exitCodes = array(
  94. 0 => 'OK',
  95. 1 => 'General error',
  96. 2 => 'Misuse of shell builtins',
  97.  
  98. 126 => 'Invoked command cannot execute',
  99. 127 => 'Command not found',
  100. 128 => 'Invalid exit argument',
  101.  
  102. // signals
  103. 129 => 'Hangup',
  104. 130 => 'Interrupt',
  105. 131 => 'Quit and dump core',
  106. 132 => 'Illegal instruction',
  107. 133 => 'Trace/breakpoint trap',
  108. 134 => 'Process aborted',
  109. 135 => 'Bus error: "access to undefined portion of memory object"',
  110. 136 => 'Floating point exception: "erroneous arithmetic operation"',
  111. 137 => 'Kill (terminate immediately)',
  112. 138 => 'User-defined 1',
  113. 139 => 'Segmentation violation',
  114. 140 => 'User-defined 2',
  115. 141 => 'Write to pipe with no one reading',
  116. 142 => 'Signal raised by alarm',
  117. 143 => 'Termination (request to terminate)',
  118. // 144 - not defined
  119. 145 => 'Child process terminated, stopped (or continued*)',
  120. 146 => 'Continue if stopped',
  121. 147 => 'Stop executing temporarily',
  122. 148 => 'Terminal stop signal',
  123. 149 => 'Background process attempting to read from tty ("in")',
  124. 150 => 'Background process attempting to write to tty ("out")',
  125. 151 => 'Urgent data available on socket',
  126. 152 => 'CPU time limit exceeded',
  127. 153 => 'File size limit exceeded',
  128. 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
  129. 155 => 'Profiling timer expired',
  130. // 156 - not defined
  131. 157 => 'Pollable event',
  132. // 158 - not defined
  133. 159 => 'Bad syscall',
  134. );
  135.  
  136. /**
  137. * Constructor.
  138. *
  139. * @param string $commandline The command line to run
  140. * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
  141. * @param array|null $env The environment variables or null to use the same environment as the current PHP process
  142. * @param mixed|null $input The input as stream resource, scalar or \Traversable, or null for no input
  143. * @param int|float|null $timeout The timeout in seconds or null to disable
  144. * @param array $options An array of options for proc_open
  145. *
  146. * @throws RuntimeException When proc_open is not installed
  147. */
  148. public function __construct($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = array())
  149. {
  150. if (!function_exists('proc_open')) {
  151. throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
  152. }
  153.  
  154. $this->commandline = $commandline;
  155. $this->cwd = $cwd;
  156.  
  157. // on Windows, if the cwd changed via chdir(), proc_open defaults to the dir where PHP was started
  158. // on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected
  159. // @see : https://bugs.php.net/bug.php?id=51800
  160. // @see : https://bugs.php.net/bug.php?id=50524
  161. if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || '\\' === DIRECTORY_SEPARATOR)) {
  162. $this->cwd = getcwd();
  163. }
  164. if (null !== $env) {
  165. $this->setEnv($env);
  166. }
  167.  
  168. $this->setInput($input);
  169. $this->setTimeout($timeout);
  170. $this->useFileHandles = '\\' === DIRECTORY_SEPARATOR;
  171. $this->pty = false;
  172. $this->enhanceWindowsCompatibility = true;
  173. $this->enhanceSigchildCompatibility = '\\' !== DIRECTORY_SEPARATOR && $this->isSigchildEnabled();
  174. $this->options = array_replace(array('suppress_errors' => true, 'binary_pipes' => true), $options);
  175. }
  176.  
  177. public function __destruct()
  178. {
  179. $this->stop(0);
  180. }
  181.  
  182. public function __clone()
  183. {
  184. $this->resetProcessData();
  185. }
  186.  
  187. /**
  188. * Runs the process.
  189. *
  190. * The callback receives the type of output (out or err) and
  191. * some bytes from the output in real-time. It allows to have feedback
  192. * from the independent process during execution.
  193. *
  194. * The STDOUT and STDERR are also available after the process is finished
  195. * via the getOutput() and getErrorOutput() methods.
  196. *
  197. * @param callable|null $callback A PHP callback to run whenever there is some
  198. * output available on STDOUT or STDERR
  199. *
  200. * @return int The exit status code
  201. *
  202. * @throws RuntimeException When process can't be launched
  203. * @throws RuntimeException When process stopped after receiving signal
  204. * @throws LogicException In case a callback is provided and output has been disabled
  205. */
  206. public function run($callback = null)
  207. {
  208. $this->start($callback);
  209.  
  210. return $this->wait();
  211. }
  212.  
  213. /**
  214. * Runs the process.
  215. *
  216. * This is identical to run() except that an exception is thrown if the process
  217. * exits with a non-zero exit code.
  218. *
  219. * @param callable|null $callback
  220. *
  221. * @return self
  222. *
  223. * @throws RuntimeException if PHP was compiled with --enable-sigchild and the enhanced sigchild compatibility mode is not enabled
  224. * @throws ProcessFailedException if the process didn't terminate successfully
  225. */
  226. public function mustRun(callable $callback = null)
  227. {
  228. if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  229. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
  230. }
  231.  
  232. if (0 !== $this->run($callback)) {
  233. throw new ProcessFailedException($this);
  234. }
  235.  
  236. return $this;
  237. }
  238.  
  239. /**
  240. * Starts the process and returns after writing the input to STDIN.
  241. *
  242. * This method blocks until all STDIN data is sent to the process then it
  243. * returns while the process runs in the background.
  244. *
  245. * The termination of the process can be awaited with wait().
  246. *
  247. * The callback receives the type of output (out or err) and some bytes from
  248. * the output in real-time while writing the standard input to the process.
  249. * It allows to have feedback from the independent process during execution.
  250. *
  251. * @param callable|null $callback A PHP callback to run whenever there is some
  252. * output available on STDOUT or STDERR
  253. *
  254. * @throws RuntimeException When process can't be launched
  255. * @throws RuntimeException When process is already running
  256. * @throws LogicException In case a callback is provided and output has been disabled
  257. */
  258. public function start(callable $callback = null)
  259. {
  260. if ($this->isRunning()) {
  261. throw new RuntimeException('Process is already running');
  262. }
  263.  
  264. $this->resetProcessData();
  265. $this->starttime = $this->lastOutputTime = microtime(true);
  266. $this->callback = $this->buildCallback($callback);
  267. $this->hasCallback = null !== $callback;
  268. $descriptors = $this->getDescriptors();
  269.  
  270. $commandline = $this->commandline;
  271. $envline = '';
  272.  
  273. if (null !== $this->env && $this->inheritEnv) {
  274. if ('\\' === DIRECTORY_SEPARATOR && !empty($this->options['bypass_shell']) && !$this->enhanceWindowsCompatibility) {
  275. throw new LogicException('The "bypass_shell" option must be false to inherit environment variables while enhanced Windows compatibility is off');
  276. }
  277. $env = '\\' === DIRECTORY_SEPARATOR ? '(SET %s)&&' : 'export %s;';
  278. foreach ($this->env as $k => $v) {
  279. $envline .= sprintf($env, ProcessUtils::escapeArgument("$k=$v"));
  280. }
  281. $env = null;
  282. } else {
  283. $env = $this->env;
  284. }
  285. if ('\\' === DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) {
  286. $commandline = 'cmd /V:ON /E:ON /D /C "('.$envline.$commandline.')';
  287. foreach ($this->processPipes->getFiles() as $offset => $filename) {
  288. $commandline .= ' '.$offset.'>'.ProcessUtils::escapeArgument($filename);
  289. }
  290. $commandline .= '"';
  291.  
  292. if (!isset($this->options['bypass_shell'])) {
  293. $this->options['bypass_shell'] = true;
  294. }
  295. } elseif (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  296. // last exit code is output on the fourth pipe and caught to work around --enable-sigchild
  297. $descriptors[3] = array('pipe', 'w');
  298.  
  299. // See https://unix.stackexchange.com/questions/71205/background-process-pipe-input
  300. $commandline = $envline.'{ ('.$this->commandline.') <&3 3<&- 3>/dev/null & } 3<&0;';
  301. $commandline .= 'pid=$!; echo $pid >&3; wait $pid; code=$?; echo $code >&3; exit $code';
  302.  
  303. // Workaround for the bug, when PTS functionality is enabled.
  304. // @see : https://bugs.php.net/69442
  305. $ptsWorkaround = fopen(__FILE__, 'r');
  306. } elseif ('' !== $envline) {
  307. $commandline = $envline.$commandline;
  308. }
  309.  
  310. $this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $env, $this->options);
  311.  
  312. if (!is_resource($this->process)) {
  313. throw new RuntimeException('Unable to launch a new process.');
  314. }
  315. $this->status = self::STATUS_STARTED;
  316.  
  317. if (isset($descriptors[3])) {
  318. $this->fallbackStatus['pid'] = (int) fgets($this->processPipes->pipes[3]);
  319. }
  320.  
  321. if ($this->tty) {
  322. return;
  323. }
  324.  
  325. $this->updateStatus(false);
  326. $this->checkTimeout();
  327. }
  328.  
  329. /**
  330. * Restarts the process.
  331. *
  332. * Be warned that the process is cloned before being started.
  333. *
  334. * @param callable|null $callback A PHP callback to run whenever there is some
  335. * output available on STDOUT or STDERR
  336. *
  337. * @return $this
  338. *
  339. * @throws RuntimeException When process can't be launched
  340. * @throws RuntimeException When process is already running
  341. *
  342. * @see start()
  343. */
  344. public function restart(callable $callback = null)
  345. {
  346. if ($this->isRunning()) {
  347. throw new RuntimeException('Process is already running');
  348. }
  349.  
  350. $process = clone $this;
  351. $process->start($callback);
  352.  
  353. return $process;
  354. }
  355.  
  356. /**
  357. * Waits for the process to terminate.
  358. *
  359. * The callback receives the type of output (out or err) and some bytes
  360. * from the output in real-time while writing the standard input to the process.
  361. * It allows to have feedback from the independent process during execution.
  362. *
  363. * @param callable|null $callback A valid PHP callback
  364. *
  365. * @return int The exitcode of the process
  366. *
  367. * @throws RuntimeException When process timed out
  368. * @throws RuntimeException When process stopped after receiving signal
  369. * @throws LogicException When process is not yet started
  370. */
  371. public function wait(callable $callback = null)
  372. {
  373. $this->requireProcessIsStarted(__FUNCTION__);
  374.  
  375. $this->updateStatus(false);
  376.  
  377. if (null !== $callback) {
  378. if (!$this->processPipes->haveReadSupport()) {
  379. $this->stop(0);
  380. throw new \LogicException('Pass the callback to the Process:start method or enableOutput to use a callback with Process::wait');
  381. }
  382. $this->callback = $this->buildCallback($callback);
  383. }
  384.  
  385. do {
  386. $this->checkTimeout();
  387. $running = '\\' === DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
  388. $this->readPipes($running, '\\' !== DIRECTORY_SEPARATOR || !$running);
  389. } while ($running);
  390.  
  391. while ($this->isRunning()) {
  392. usleep(1000);
  393. }
  394.  
  395. if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {
  396. throw new RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig']));
  397. }
  398.  
  399. return $this->exitcode;
  400. }
  401.  
  402. /**
  403. * Returns the Pid (process identifier), if applicable.
  404. *
  405. * @return int|null The process id if running, null otherwise
  406. */
  407. public function getPid()
  408. {
  409. return $this->isRunning() ? $this->processInformation['pid'] : null;
  410. }
  411.  
  412. /**
  413. * Sends a POSIX signal to the process.
  414. *
  415. * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
  416. *
  417. * @return $this
  418. *
  419. * @throws LogicException In case the process is not running
  420. * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed
  421. * @throws RuntimeException In case of failure
  422. */
  423. public function signal($signal)
  424. {
  425. $this->doSignal($signal, true);
  426.  
  427. return $this;
  428. }
  429.  
  430. /**
  431. * Disables fetching output and error output from the underlying process.
  432. *
  433. * @return $this
  434. *
  435. * @throws RuntimeException In case the process is already running
  436. * @throws LogicException if an idle timeout is set
  437. */
  438. public function disableOutput()
  439. {
  440. if ($this->isRunning()) {
  441. throw new RuntimeException('Disabling output while the process is running is not possible.');
  442. }
  443. if (null !== $this->idleTimeout) {
  444. throw new LogicException('Output can not be disabled while an idle timeout is set.');
  445. }
  446.  
  447. $this->outputDisabled = true;
  448.  
  449. return $this;
  450. }
  451.  
  452. /**
  453. * Enables fetching output and error output from the underlying process.
  454. *
  455. * @return $this
  456. *
  457. * @throws RuntimeException In case the process is already running
  458. */
  459. public function enableOutput()
  460. {
  461. if ($this->isRunning()) {
  462. throw new RuntimeException('Enabling output while the process is running is not possible.');
  463. }
  464.  
  465. $this->outputDisabled = false;
  466.  
  467. return $this;
  468. }
  469.  
  470. /**
  471. * Returns true in case the output is disabled, false otherwise.
  472. *
  473. * @return bool
  474. */
  475. public function isOutputDisabled()
  476. {
  477. return $this->outputDisabled;
  478. }
  479.  
  480. /**
  481. * Returns the current output of the process (STDOUT).
  482. *
  483. * @return string The process output
  484. *
  485. * @throws LogicException in case the output has been disabled
  486. * @throws LogicException In case the process is not started
  487. */
  488. public function getOutput()
  489. {
  490. $this->readPipesForOutput(__FUNCTION__);
  491.  
  492. if (false === $ret = stream_get_contents($this->stdout, -1, 0)) {
  493. return '';
  494. }
  495.  
  496. return $ret;
  497. }
  498.  
  499. /**
  500. * Returns the output incrementally.
  501. *
  502. * In comparison with the getOutput method which always return the whole
  503. * output, this one returns the new output since the last call.
  504. *
  505. * @return string The process output since the last call
  506. *
  507. * @throws LogicException in case the output has been disabled
  508. * @throws LogicException In case the process is not started
  509. */
  510. public function getIncrementalOutput()
  511. {
  512. $this->readPipesForOutput(__FUNCTION__);
  513.  
  514. $latest = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
  515. $this->incrementalOutputOffset = ftell($this->stdout);
  516.  
  517. if (false === $latest) {
  518. return '';
  519. }
  520.  
  521. return $latest;
  522. }
  523.  
  524. /**
  525. * Returns an iterator to the output of the process, with the output type as keys (Process::OUT/ERR).
  526. *
  527. * @param int $flags A bit field of Process::ITER_* flags
  528. *
  529. * @throws LogicException in case the output has been disabled
  530. * @throws LogicException In case the process is not started
  531. *
  532. * @return \Generator
  533. */
  534. public function getIterator($flags = 0)
  535. {
  536. $this->readPipesForOutput(__FUNCTION__, false);
  537.  
  538. $clearOutput = !(self::ITER_KEEP_OUTPUT & $flags);
  539. $blocking = !(self::ITER_NON_BLOCKING & $flags);
  540. $yieldOut = !(self::ITER_SKIP_OUT & $flags);
  541. $yieldErr = !(self::ITER_SKIP_ERR & $flags);
  542.  
  543. while (null !== $this->callback || ($yieldOut && !feof($this->stdout)) || ($yieldErr && !feof($this->stderr))) {
  544. if ($yieldOut) {
  545. $out = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
  546.  
  547. if (isset($out[0])) {
  548. if ($clearOutput) {
  549. $this->clearOutput();
  550. } else {
  551. $this->incrementalOutputOffset = ftell($this->stdout);
  552. }
  553.  
  554. yield self::OUT => $out;
  555. }
  556. }
  557.  
  558. if ($yieldErr) {
  559. $err = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
  560.  
  561. if (isset($err[0])) {
  562. if ($clearOutput) {
  563. $this->clearErrorOutput();
  564. } else {
  565. $this->incrementalErrorOutputOffset = ftell($this->stderr);
  566. }
  567.  
  568. yield self::ERR => $err;
  569. }
  570. }
  571.  
  572. if (!$blocking && !isset($out[0]) && !isset($err[0])) {
  573. yield self::OUT => '';
  574. }
  575.  
  576. $this->checkTimeout();
  577. $this->readPipesForOutput(__FUNCTION__, $blocking);
  578. }
  579. }
  580.  
  581. /**
  582. * Clears the process output.
  583. *
  584. * @return $this
  585. */
  586. public function clearOutput()
  587. {
  588. ftruncate($this->stdout, 0);
  589. fseek($this->stdout, 0);
  590. $this->incrementalOutputOffset = 0;
  591.  
  592. return $this;
  593. }
  594.  
  595. /**
  596. * Returns the current error output of the process (STDERR).
  597. *
  598. * @return string The process error output
  599. *
  600. * @throws LogicException in case the output has been disabled
  601. * @throws LogicException In case the process is not started
  602. */
  603. public function getErrorOutput()
  604. {
  605. $this->readPipesForOutput(__FUNCTION__);
  606.  
  607. if (false === $ret = stream_get_contents($this->stderr, -1, 0)) {
  608. return '';
  609. }
  610.  
  611. return $ret;
  612. }
  613.  
  614. /**
  615. * Returns the errorOutput incrementally.
  616. *
  617. * In comparison with the getErrorOutput method which always return the
  618. * whole error output, this one returns the new error output since the last
  619. * call.
  620. *
  621. * @return string The process error output since the last call
  622. *
  623. * @throws LogicException in case the output has been disabled
  624. * @throws LogicException In case the process is not started
  625. */
  626. public function getIncrementalErrorOutput()
  627. {
  628. $this->readPipesForOutput(__FUNCTION__);
  629.  
  630. $latest = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
  631. $this->incrementalErrorOutputOffset = ftell($this->stderr);
  632.  
  633. if (false === $latest) {
  634. return '';
  635. }
  636.  
  637. return $latest;
  638. }
  639.  
  640. /**
  641. * Clears the process output.
  642. *
  643. * @return $this
  644. */
  645. public function clearErrorOutput()
  646. {
  647. ftruncate($this->stderr, 0);
  648. fseek($this->stderr, 0);
  649. $this->incrementalErrorOutputOffset = 0;
  650.  
  651. return $this;
  652. }
  653.  
  654. /**
  655. * Returns the exit code returned by the process.
  656. *
  657. * @return null|int The exit status code, null if the Process is not terminated
  658. *
  659. * @throws RuntimeException In case --enable-sigchild is activated and the sigchild compatibility mode is disabled
  660. */
  661. public function getExitCode()
  662. {
  663. if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  664. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
  665. }
  666.  
  667. $this->updateStatus(false);
  668.  
  669. return $this->exitcode;
  670. }
  671.  
  672. /**
  673. * Returns a string representation for the exit code returned by the process.
  674. *
  675. * This method relies on the Unix exit code status standardization
  676. * and might not be relevant for other operating systems.
  677. *
  678. * @return null|string A string representation for the exit status code, null if the Process is not terminated
  679. *
  680. * @see http://tldp.org/LDP/abs/html/exitcodes.html
  681. * @see http://en.wikipedia.org/wiki/Unix_signal
  682. */
  683. public function getExitCodeText()
  684. {
  685. if (null === $exitcode = $this->getExitCode()) {
  686. return;
  687. }
  688.  
  689. return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
  690. }
  691.  
  692. /**
  693. * Checks if the process ended successfully.
  694. *
  695. * @return bool true if the process ended successfully, false otherwise
  696. */
  697. public function isSuccessful()
  698. {
  699. return 0 === $this->getExitCode();
  700. }
  701.  
  702. /**
  703. * Returns true if the child process has been terminated by an uncaught signal.
  704. *
  705. * It always returns false on Windows.
  706. *
  707. * @return bool
  708. *
  709. * @throws RuntimeException In case --enable-sigchild is activated
  710. * @throws LogicException In case the process is not terminated
  711. */
  712. public function hasBeenSignaled()
  713. {
  714. $this->requireProcessIsTerminated(__FUNCTION__);
  715.  
  716. if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  717. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  718. }
  719.  
  720. return $this->processInformation['signaled'];
  721. }
  722.  
  723. /**
  724. * Returns the number of the signal that caused the child process to terminate its execution.
  725. *
  726. * It is only meaningful if hasBeenSignaled() returns true.
  727. *
  728. * @return int
  729. *
  730. * @throws RuntimeException In case --enable-sigchild is activated
  731. * @throws LogicException In case the process is not terminated
  732. */
  733. public function getTermSignal()
  734. {
  735. $this->requireProcessIsTerminated(__FUNCTION__);
  736.  
  737. if ($this->isSigchildEnabled() && (!$this->enhanceSigchildCompatibility || -1 === $this->processInformation['termsig'])) {
  738. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  739. }
  740.  
  741. return $this->processInformation['termsig'];
  742. }
  743.  
  744. /**
  745. * Returns true if the child process has been stopped by a signal.
  746. *
  747. * It always returns false on Windows.
  748. *
  749. * @return bool
  750. *
  751. * @throws LogicException In case the process is not terminated
  752. */
  753. public function hasBeenStopped()
  754. {
  755. $this->requireProcessIsTerminated(__FUNCTION__);
  756.  
  757. return $this->processInformation['stopped'];
  758. }
  759.  
  760. /**
  761. * Returns the number of the signal that caused the child process to stop its execution.
  762. *
  763. * It is only meaningful if hasBeenStopped() returns true.
  764. *
  765. * @return int
  766. *
  767. * @throws LogicException In case the process is not terminated
  768. */
  769. public function getStopSignal()
  770. {
  771. $this->requireProcessIsTerminated(__FUNCTION__);
  772.  
  773. return $this->processInformation['stopsig'];
  774. }
  775.  
  776. /**
  777. * Checks if the process is currently running.
  778. *
  779. * @return bool true if the process is currently running, false otherwise
  780. */
  781. public function isRunning()
  782. {
  783. if (self::STATUS_STARTED !== $this->status) {
  784. return false;
  785. }
  786.  
  787. $this->updateStatus(false);
  788.  
  789. return $this->processInformation['running'];
  790. }
  791.  
  792. /**
  793. * Checks if the process has been started with no regard to the current state.
  794. *
  795. * @return bool true if status is ready, false otherwise
  796. */
  797. public function isStarted()
  798. {
  799. return $this->status != self::STATUS_READY;
  800. }
  801.  
  802. /**
  803. * Checks if the process is terminated.
  804. *
  805. * @return bool true if process is terminated, false otherwise
  806. */
  807. public function isTerminated()
  808. {
  809. $this->updateStatus(false);
  810.  
  811. return $this->status == self::STATUS_TERMINATED;
  812. }
  813.  
  814. /**
  815. * Gets the process status.
  816. *
  817. * The status is one of: ready, started, terminated.
  818. *
  819. * @return string The current process status
  820. */
  821. public function getStatus()
  822. {
  823. $this->updateStatus(false);
  824.  
  825. return $this->status;
  826. }
  827.  
  828. /**
  829. * Stops the process.
  830. *
  831. * @param int|float $timeout The timeout in seconds
  832. * @param int $signal A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL (9)
  833. *
  834. * @return int The exit-code of the process
  835. */
  836. public function stop($timeout = 10, $signal = null)
  837. {
  838. $timeoutMicro = microtime(true) + $timeout;
  839. if ($this->isRunning()) {
  840. // given `SIGTERM` may not be defined and that `proc_terminate` uses the constant value and not the constant itself, we use the same here
  841. $this->doSignal(15, false);
  842. do {
  843. usleep(1000);
  844. } while ($this->isRunning() && microtime(true) < $timeoutMicro);
  845.  
  846. if ($this->isRunning()) {
  847. // Avoid exception here: process is supposed to be running, but it might have stopped just
  848. // after this line. In any case, let's silently discard the error, we cannot do anything.
  849. $this->doSignal($signal ?: 9, false);
  850. }
  851. }
  852.  
  853. if ($this->isRunning()) {
  854. if (isset($this->fallbackStatus['pid'])) {
  855. unset($this->fallbackStatus['pid']);
  856.  
  857. return $this->stop(0, $signal);
  858. }
  859. $this->close();
  860. }
  861.  
  862. return $this->exitcode;
  863. }
  864.  
  865. /**
  866. * Adds a line to the STDOUT stream.
  867. *
  868. * @internal
  869. *
  870. * @param string $line The line to append
  871. */
  872. public function addOutput($line)
  873. {
  874. $this->lastOutputTime = microtime(true);
  875.  
  876. fseek($this->stdout, 0, SEEK_END);
  877. fwrite($this->stdout, $line);
  878. fseek($this->stdout, $this->incrementalOutputOffset);
  879. }
  880.  
  881. /**
  882. * Adds a line to the STDERR stream.
  883. *
  884. * @internal
  885. *
  886. * @param string $line The line to append
  887. */
  888. public function addErrorOutput($line)
  889. {
  890. $this->lastOutputTime = microtime(true);
  891.  
  892. fseek($this->stderr, 0, SEEK_END);
  893. fwrite($this->stderr, $line);
  894. fseek($this->stderr, $this->incrementalErrorOutputOffset);
  895. }
  896.  
  897. /**
  898. * Gets the command line to be executed.
  899. *
  900. * @return string The command to execute
  901. */
  902. public function getCommandLine()
  903. {
  904. return $this->commandline;
  905. }
  906.  
  907. /**
  908. * Sets the command line to be executed.
  909. *
  910. * @param string $commandline The command to execute
  911. *
  912. * @return self The current Process instance
  913. */
  914. public function setCommandLine($commandline)
  915. {
  916. $this->commandline = $commandline;
  917.  
  918. return $this;
  919. }
  920.  
  921. /**
  922. * Gets the process timeout (max. runtime).
  923. *
  924. * @return float|null The timeout in seconds or null if it's disabled
  925. */
  926. public function getTimeout()
  927. {
  928. return $this->timeout;
  929. }
  930.  
  931. /**
  932. * Gets the process idle timeout (max. time since last output).
  933. *
  934. * @return float|null The timeout in seconds or null if it's disabled
  935. */
  936. public function getIdleTimeout()
  937. {
  938. return $this->idleTimeout;
  939. }
  940.  
  941. /**
  942. * Sets the process timeout (max. runtime).
  943. *
  944. * To disable the timeout, set this value to null.
  945. *
  946. * @param int|float|null $timeout The timeout in seconds
  947. *
  948. * @return self The current Process instance
  949. *
  950. * @throws InvalidArgumentException if the timeout is negative
  951. */
  952. public function setTimeout($timeout)
  953. {
  954. $this->timeout = $this->validateTimeout($timeout);
  955.  
  956. return $this;
  957. }
  958.  
  959. /**
  960. * Sets the process idle timeout (max. time since last output).
  961. *
  962. * To disable the timeout, set this value to null.
  963. *
  964. * @param int|float|null $timeout The timeout in seconds
  965. *
  966. * @return self The current Process instance
  967. *
  968. * @throws LogicException if the output is disabled
  969. * @throws InvalidArgumentException if the timeout is negative
  970. */
  971. public function setIdleTimeout($timeout)
  972. {
  973. if (null !== $timeout && $this->outputDisabled) {
  974. throw new LogicException('Idle timeout can not be set while the output is disabled.');
  975. }
  976.  
  977. $this->idleTimeout = $this->validateTimeout($timeout);
  978.  
  979. return $this;
  980. }
  981.  
  982. /**
  983. * Enables or disables the TTY mode.
  984. *
  985. * @param bool $tty True to enabled and false to disable
  986. *
  987. * @return self The current Process instance
  988. *
  989. * @throws RuntimeException In case the TTY mode is not supported
  990. */
  991. public function setTty($tty)
  992. {
  993. if ('\\' === DIRECTORY_SEPARATOR && $tty) {
  994. throw new RuntimeException('TTY mode is not supported on Windows platform.');
  995. }
  996. if ($tty) {
  997. static $isTtySupported;
  998.  
  999. if (null === $isTtySupported) {
  1000. $isTtySupported = (bool) @proc_open('echo 1 >/dev/null', array(array('file', '/dev/tty', 'r'), array('file', '/dev/tty', 'w'), array('file', '/dev/tty', 'w')), $pipes);
  1001. }
  1002.  
  1003. if (!$isTtySupported) {
  1004. throw new RuntimeException('TTY mode requires /dev/tty to be read/writable.');
  1005. }
  1006. }
  1007.  
  1008. $this->tty = (bool) $tty;
  1009.  
  1010. return $this;
  1011. }
  1012.  
  1013. /**
  1014. * Checks if the TTY mode is enabled.
  1015. *
  1016. * @return bool true if the TTY mode is enabled, false otherwise
  1017. */
  1018. public function isTty()
  1019. {
  1020. return $this->tty;
  1021. }
  1022.  
  1023. /**
  1024. * Sets PTY mode.
  1025. *
  1026. * @param bool $bool
  1027. *
  1028. * @return self
  1029. */
  1030. public function setPty($bool)
  1031. {
  1032. $this->pty = (bool) $bool;
  1033.  
  1034. return $this;
  1035. }
  1036.  
  1037. /**
  1038. * Returns PTY state.
  1039. *
  1040. * @return bool
  1041. */
  1042. public function isPty()
  1043. {
  1044. return $this->pty;
  1045. }
  1046.  
  1047. /**
  1048. * Gets the working directory.
  1049. *
  1050. * @return string|null The current working directory or null on failure
  1051. */
  1052. public function getWorkingDirectory()
  1053. {
  1054. if (null === $this->cwd) {
  1055. // getcwd() will return false if any one of the parent directories does not have
  1056. // the readable or search mode set, even if the current directory does
  1057. return getcwd() ?: null;
  1058. }
  1059.  
  1060. return $this->cwd;
  1061. }
  1062.  
  1063. /**
  1064. * Sets the current working directory.
  1065. *
  1066. * @param string $cwd The new working directory
  1067. *
  1068. * @return self The current Process instance
  1069. */
  1070. public function setWorkingDirectory($cwd)
  1071. {
  1072. $this->cwd = $cwd;
  1073.  
  1074. return $this;
  1075. }
  1076.  
  1077. /**
  1078. * Gets the environment variables.
  1079. *
  1080. * @return array The current environment variables
  1081. */
  1082. public function getEnv()
  1083. {
  1084. return $this->env;
  1085. }
  1086.  
  1087. /**
  1088. * Sets the environment variables.
  1089. *
  1090. * An environment variable value should be a string.
  1091. * If it is an array, the variable is ignored.
  1092. *
  1093. * That happens in PHP when 'argv' is registered into
  1094. * the $_ENV array for instance.
  1095. *
  1096. * @param array $env The new environment variables
  1097. *
  1098. * @return self The current Process instance
  1099. */
  1100. public function setEnv(array $env)
  1101. {
  1102. // Process can not handle env values that are arrays
  1103. $env = array_filter($env, function ($value) {
  1104. return !is_array($value);
  1105. });
  1106.  
  1107. $this->env = array();
  1108. foreach ($env as $key => $value) {
  1109. $this->env[$key] = (string) $value;
  1110. }
  1111.  
  1112. return $this;
  1113. }
  1114.  
  1115. /**
  1116. * Gets the Process input.
  1117. *
  1118. * @return resource|string|\Iterator|null The Process input
  1119. */
  1120. public function getInput()
  1121. {
  1122. return $this->input;
  1123. }
  1124.  
  1125. /**
  1126. * Sets the input.
  1127. *
  1128. * This content will be passed to the underlying process standard input.
  1129. *
  1130. * @param resource|scalar|\Traversable|null $input The content
  1131. *
  1132. * @return self The current Process instance
  1133. *
  1134. * @throws LogicException In case the process is running
  1135. */
  1136. public function setInput($input)
  1137. {
  1138. if ($this->isRunning()) {
  1139. throw new LogicException('Input can not be set while the process is running.');
  1140. }
  1141.  
  1142. $this->input = ProcessUtils::validateInput(__METHOD__, $input);
  1143.  
  1144. return $this;
  1145. }
  1146.  
  1147. /**
  1148. * Gets the options for proc_open.
  1149. *
  1150. * @return array The current options
  1151. */
  1152. public function getOptions()
  1153. {
  1154. return $this->options;
  1155. }
  1156.  
  1157. /**
  1158. * Sets the options for proc_open.
  1159. *
  1160. * @param array $options The new options
  1161. *
  1162. * @return self The current Process instance
  1163. */
  1164. public function setOptions(array $options)
  1165. {
  1166. $this->options = $options;
  1167.  
  1168. return $this;
  1169. }
  1170.  
  1171. /**
  1172. * Gets whether or not Windows compatibility is enabled.
  1173. *
  1174. * This is true by default.
  1175. *
  1176. * @return bool
  1177. */
  1178. public function getEnhanceWindowsCompatibility()
  1179. {
  1180. return $this->enhanceWindowsCompatibility;
  1181. }
  1182.  
  1183. /**
  1184. * Sets whether or not Windows compatibility is enabled.
  1185. *
  1186. * @param bool $enhance
  1187. *
  1188. * @return self The current Process instance
  1189. */
  1190. public function setEnhanceWindowsCompatibility($enhance)
  1191. {
  1192. $this->enhanceWindowsCompatibility = (bool) $enhance;
  1193.  
  1194. return $this;
  1195. }
  1196.  
  1197. /**
  1198. * Returns whether sigchild compatibility mode is activated or not.
  1199. *
  1200. * @return bool
  1201. */
  1202. public function getEnhanceSigchildCompatibility()
  1203. {
  1204. return $this->enhanceSigchildCompatibility;
  1205. }
  1206.  
  1207. /**
  1208. * Activates sigchild compatibility mode.
  1209. *
  1210. * Sigchild compatibility mode is required to get the exit code and
  1211. * determine the success of a process when PHP has been compiled with
  1212. * the --enable-sigchild option
  1213. *
  1214. * @param bool $enhance
  1215. *
  1216. * @return self The current Process instance
  1217. */
  1218. public function setEnhanceSigchildCompatibility($enhance)
  1219. {
  1220. $this->enhanceSigchildCompatibility = (bool) $enhance;
  1221.  
  1222. return $this;
  1223. }
  1224.  
  1225. /**
  1226. * Sets whether environment variables will be inherited or not.
  1227. *
  1228. * @param bool $inheritEnv
  1229. *
  1230. * @return self The current Process instance
  1231. */
  1232. public function inheritEnvironmentVariables($inheritEnv = true)
  1233. {
  1234. $this->inheritEnv = (bool) $inheritEnv;
  1235.  
  1236. return $this;
  1237. }
  1238.  
  1239. /**
  1240. * Returns whether environment variables will be inherited or not.
  1241. *
  1242. * @return bool
  1243. */
  1244. public function areEnvironmentVariablesInherited()
  1245. {
  1246. return $this->inheritEnv;
  1247. }
  1248.  
  1249. /**
  1250. * Performs a check between the timeout definition and the time the process started.
  1251. *
  1252. * In case you run a background process (with the start method), you should
  1253. * trigger this method regularly to ensure the process timeout
  1254. *
  1255. * @throws ProcessTimedOutException In case the timeout was reached
  1256. */
  1257. public function checkTimeout()
  1258. {
  1259. if ($this->status !== self::STATUS_STARTED) {
  1260. return;
  1261. }
  1262.  
  1263. if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
  1264. $this->stop(0);
  1265.  
  1266. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL);
  1267. }
  1268.  
  1269. if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
  1270. $this->stop(0);
  1271.  
  1272. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE);
  1273. }
  1274. }
  1275.  
  1276. /**
  1277. * Returns whether PTY is supported on the current operating system.
  1278. *
  1279. * @return bool
  1280. */
  1281. public static function isPtySupported()
  1282. {
  1283. static $result;
  1284.  
  1285. if (null !== $result) {
  1286. return $result;
  1287. }
  1288.  
  1289. if ('\\' === DIRECTORY_SEPARATOR) {
  1290. return $result = false;
  1291. }
  1292.  
  1293. return $result = (bool) @proc_open('echo 1 >/dev/null', array(array('pty'), array('pty'), array('pty')), $pipes);
  1294. }
  1295.  
  1296. /**
  1297. * Creates the descriptors needed by the proc_open.
  1298. *
  1299. * @return array
  1300. */
  1301. private function getDescriptors()
  1302. {
  1303. if ($this->input instanceof \Iterator) {
  1304. $this->input->rewind();
  1305. }
  1306. if ('\\' === DIRECTORY_SEPARATOR) {
  1307. $this->processPipes = new WindowsPipes($this->input, !$this->outputDisabled || $this->hasCallback);
  1308. } else {
  1309. $this->processPipes = new UnixPipes($this->isTty(), $this->isPty(), $this->input, !$this->outputDisabled || $this->hasCallback);
  1310. }
  1311.  
  1312. return $this->processPipes->getDescriptors();
  1313. }
  1314.  
  1315. /**
  1316. * Builds up the callback used by wait().
  1317. *
  1318. * The callbacks adds all occurred output to the specific buffer and calls
  1319. * the user callback (if present) with the received output.
  1320. *
  1321. * @param callable|null $callback The user defined PHP callback
  1322. *
  1323. * @return \Closure A PHP closure
  1324. */
  1325. protected function buildCallback(callable $callback = null)
  1326. {
  1327. if ($this->outputDisabled) {
  1328. return function ($type, $data) use ($callback) {
  1329. if (null !== $callback) {
  1330. call_user_func($callback, $type, $data);
  1331. }
  1332. };
  1333. }
  1334.  
  1335. $out = self::OUT;
  1336.  
  1337. return function ($type, $data) use ($callback, $out) {
  1338. if ($out == $type) {
  1339. $this->addOutput($data);
  1340. } else {
  1341. $this->addErrorOutput($data);
  1342. }
  1343.  
  1344. if (null !== $callback) {
  1345. call_user_func($callback, $type, $data);
  1346. }
  1347. };
  1348. }
  1349.  
  1350. /**
  1351. * Updates the status of the process, reads pipes.
  1352. *
  1353. * @param bool $blocking Whether to use a blocking read call
  1354. */
  1355. protected function updateStatus($blocking)
  1356. {
  1357. if (self::STATUS_STARTED !== $this->status) {
  1358. return;
  1359. }
  1360.  
  1361. $this->processInformation = proc_get_status($this->process);
  1362. $running = $this->processInformation['running'];
  1363.  
  1364. $this->readPipes($running && $blocking, '\\' !== DIRECTORY_SEPARATOR || !$running);
  1365.  
  1366. if ($this->fallbackStatus && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  1367. $this->processInformation = $this->fallbackStatus + $this->processInformation;
  1368. }
  1369.  
  1370. if (!$running) {
  1371. $this->close();
  1372. }
  1373. }
  1374.  
  1375. /**
  1376. * Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
  1377. *
  1378. * @return bool
  1379. */
  1380. protected function isSigchildEnabled()
  1381. {
  1382. if (null !== self::$sigchild) {
  1383. return self::$sigchild;
  1384. }
  1385.  
  1386. if (!function_exists('phpinfo') || defined('HHVM_VERSION')) {
  1387. return self::$sigchild = false;
  1388. }
  1389.  
  1390. ob_start();
  1391. phpinfo(INFO_GENERAL);
  1392.  
  1393. return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  1394. }
  1395.  
  1396. /**
  1397. * Reads pipes for the freshest output.
  1398. *
  1399. * @param string $caller The name of the method that needs fresh outputs
  1400. * @param bool $blocking Whether to use blocking calls or not
  1401. *
  1402. * @throws LogicException in case output has been disabled or process is not started
  1403. */
  1404. private function readPipesForOutput($caller, $blocking = false)
  1405. {
  1406. if ($this->outputDisabled) {
  1407. throw new LogicException('Output has been disabled.');
  1408. }
  1409.  
  1410. $this->requireProcessIsStarted($caller);
  1411.  
  1412. $this->updateStatus($blocking);
  1413. }
  1414.  
  1415. /**
  1416. * Validates and returns the filtered timeout.
  1417. *
  1418. * @param int|float|null $timeout
  1419. *
  1420. * @return float|null
  1421. *
  1422. * @throws InvalidArgumentException if the given timeout is a negative number
  1423. */
  1424. private function validateTimeout($timeout)
  1425. {
  1426. $timeout = (float) $timeout;
  1427.  
  1428. if (0.0 === $timeout) {
  1429. $timeout = null;
  1430. } elseif ($timeout < 0) {
  1431. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  1432. }
  1433.  
  1434. return $timeout;
  1435. }
  1436.  
  1437. /**
  1438. * Reads pipes, executes callback.
  1439. *
  1440. * @param bool $blocking Whether to use blocking calls or not
  1441. * @param bool $close Whether to close file handles or not
  1442. */
  1443. private function readPipes($blocking, $close)
  1444. {
  1445. $result = $this->processPipes->readAndWrite($blocking, $close);
  1446.  
  1447. $callback = $this->callback;
  1448. foreach ($result as $type => $data) {
  1449. if (3 !== $type) {
  1450. $callback($type === self::STDOUT ? self::OUT : self::ERR, $data);
  1451. } elseif (!isset($this->fallbackStatus['signaled'])) {
  1452. $this->fallbackStatus['exitcode'] = (int) $data;
  1453. }
  1454. }
  1455. }
  1456.  
  1457. /**
  1458. * Closes process resource, closes file handles, sets the exitcode.
  1459. *
  1460. * @return int The exitcode
  1461. */
  1462. private function close()
  1463. {
  1464. $this->processPipes->close();
  1465. if (is_resource($this->process)) {
  1466. proc_close($this->process);
  1467. }
  1468. $this->exitcode = $this->processInformation['exitcode'];
  1469. $this->status = self::STATUS_TERMINATED;
  1470.  
  1471. if (-1 === $this->exitcode) {
  1472. if ($this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
  1473. // if process has been signaled, no exitcode but a valid termsig, apply Unix convention
  1474. $this->exitcode = 128 + $this->processInformation['termsig'];
  1475. } elseif ($this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  1476. $this->processInformation['signaled'] = true;
  1477. $this->processInformation['termsig'] = -1;
  1478. }
  1479. }
  1480.  
  1481. // Free memory from self-reference callback created by buildCallback
  1482. // Doing so in other contexts like __destruct or by garbage collector is ineffective
  1483. // Now pipes are closed, so the callback is no longer necessary
  1484. $this->callback = null;
  1485.  
  1486. return $this->exitcode;
  1487. }
  1488.  
  1489. /**
  1490. * Resets data related to the latest run of the process.
  1491. */
  1492. private function resetProcessData()
  1493. {
  1494. $this->starttime = null;
  1495. $this->callback = null;
  1496. $this->exitcode = null;
  1497. $this->fallbackStatus = array();
  1498. $this->processInformation = null;
  1499. $this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'wb+');
  1500. $this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'wb+');
  1501. $this->process = null;
  1502. $this->latestSignal = null;
  1503. $this->status = self::STATUS_READY;
  1504. $this->incrementalOutputOffset = 0;
  1505. $this->incrementalErrorOutputOffset = 0;
  1506. }
  1507.  
  1508. /**
  1509. * Sends a POSIX signal to the process.
  1510. *
  1511. * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
  1512. * @param bool $throwException Whether to throw exception in case signal failed
  1513. *
  1514. * @return bool True if the signal was sent successfully, false otherwise
  1515. *
  1516. * @throws LogicException In case the process is not running
  1517. * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed
  1518. * @throws RuntimeException In case of failure
  1519. */
  1520. private function doSignal($signal, $throwException)
  1521. {
  1522. if (null === $pid = $this->getPid()) {
  1523. if ($throwException) {
  1524. throw new LogicException('Can not send signal on a non running process.');
  1525. }
  1526.  
  1527. return false;
  1528. }
  1529.  
  1530. if ('\\' === DIRECTORY_SEPARATOR) {
  1531. exec(sprintf('taskkill /F /T /PID %d 2>&1', $pid), $output, $exitCode);
  1532. if ($exitCode && $this->isRunning()) {
  1533. if ($throwException) {
  1534. throw new RuntimeException(sprintf('Unable to kill the process (%s).', implode(' ', $output)));
  1535. }
  1536.  
  1537. return false;
  1538. }
  1539. } else {
  1540. if (!$this->enhanceSigchildCompatibility || !$this->isSigchildEnabled()) {
  1541. $ok = @proc_terminate($this->process, $signal);
  1542. } elseif (function_exists('posix_kill')) {
  1543. $ok = @posix_kill($pid, $signal);
  1544. } elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), array(2 => array('pipe', 'w')), $pipes)) {
  1545. $ok = false === fgets($pipes[2]);
  1546. }
  1547. if (!$ok) {
  1548. if ($throwException) {
  1549. throw new RuntimeException(sprintf('Error while sending signal `%s`.', $signal));
  1550. }
  1551.  
  1552. return false;
  1553. }
  1554. }
  1555.  
  1556. $this->latestSignal = (int) $signal;
  1557. $this->fallbackStatus['signaled'] = true;
  1558. $this->fallbackStatus['exitcode'] = -1;
  1559. $this->fallbackStatus['termsig'] = $this->latestSignal;
  1560.  
  1561. return true;
  1562. }
  1563.  
  1564. /**
  1565. * Ensures the process is running or terminated, throws a LogicException if the process has a not started.
  1566. *
  1567. * @param string $functionName The function name that was called
  1568. *
  1569. * @throws LogicException If the process has not run.
  1570. */
  1571. private function requireProcessIsStarted($functionName)
  1572. {
  1573. if (!$this->isStarted()) {
  1574. throw new LogicException(sprintf('Process must be started before calling %s.', $functionName));
  1575. }
  1576. }
  1577.  
  1578. /**
  1579. * Ensures the process is terminated, throws a LogicException if the process has a status different than `terminated`.
  1580. *
  1581. * @param string $functionName The function name that was called
  1582. *
  1583. * @throws LogicException If the process is not yet terminated.
  1584. */
  1585. private function requireProcessIsTerminated($functionName)
  1586. {
  1587. if (!$this->isTerminated()) {
  1588. throw new LogicException(sprintf('Process must be terminated before calling %s.', $functionName));
  1589. }
  1590. }
  1591. }