Process.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Process;
  11. use Symfony\Component\Process\Exception\InvalidArgumentException;
  12. use Symfony\Component\Process\Exception\RuntimeException;
  13. /**
  14. * Process is a thin wrapper around proc_* functions to ease
  15. * start independent PHP processes.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. *
  19. * @api
  20. */
  21. class Process
  22. {
  23. const ERR = 'err';
  24. const OUT = 'out';
  25. const STATUS_READY = 'ready';
  26. const STATUS_STARTED = 'started';
  27. const STATUS_TERMINATED = 'terminated';
  28. const STDIN = 0;
  29. const STDOUT = 1;
  30. const STDERR = 2;
  31. // Timeout Precision in seconds.
  32. const TIMEOUT_PRECISION = 0.2;
  33. private $callback;
  34. private $commandline;
  35. private $cwd;
  36. private $env;
  37. private $stdin;
  38. private $starttime;
  39. private $timeout;
  40. private $options;
  41. private $exitcode;
  42. private $fallbackExitcode;
  43. private $processInformation;
  44. private $stdout;
  45. private $stderr;
  46. private $enhanceWindowsCompatibility;
  47. private $enhanceSigchildCompatibility;
  48. private $process;
  49. private $status = self::STATUS_READY;
  50. private $incrementalOutputOffset;
  51. private $incrementalErrorOutputOffset;
  52. private $useFileHandles = false;
  53. /** @var ProcessPipes */
  54. private $processPipes;
  55. private static $sigchild;
  56. /**
  57. * Exit codes translation table.
  58. *
  59. * User-defined errors must use exit codes in the 64-113 range.
  60. *
  61. * @var array
  62. */
  63. public static $exitCodes = array(
  64. 0 => 'OK',
  65. 1 => 'General error',
  66. 2 => 'Misuse of shell builtins',
  67. 126 => 'Invoked command cannot execute',
  68. 127 => 'Command not found',
  69. 128 => 'Invalid exit argument',
  70. // signals
  71. 129 => 'Hangup',
  72. 130 => 'Interrupt',
  73. 131 => 'Quit and dump core',
  74. 132 => 'Illegal instruction',
  75. 133 => 'Trace/breakpoint trap',
  76. 134 => 'Process aborted',
  77. 135 => 'Bus error: "access to undefined portion of memory object"',
  78. 136 => 'Floating point exception: "erroneous arithmetic operation"',
  79. 137 => 'Kill (terminate immediately)',
  80. 138 => 'User-defined 1',
  81. 139 => 'Segmentation violation',
  82. 140 => 'User-defined 2',
  83. 141 => 'Write to pipe with no one reading',
  84. 142 => 'Signal raised by alarm',
  85. 143 => 'Termination (request to terminate)',
  86. // 144 - not defined
  87. 145 => 'Child process terminated, stopped (or continued*)',
  88. 146 => 'Continue if stopped',
  89. 147 => 'Stop executing temporarily',
  90. 148 => 'Terminal stop signal',
  91. 149 => 'Background process attempting to read from tty ("in")',
  92. 150 => 'Background process attempting to write to tty ("out")',
  93. 151 => 'Urgent data available on socket',
  94. 152 => 'CPU time limit exceeded',
  95. 153 => 'File size limit exceeded',
  96. 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
  97. 155 => 'Profiling timer expired',
  98. // 156 - not defined
  99. 157 => 'Pollable event',
  100. // 158 - not defined
  101. 159 => 'Bad syscall',
  102. );
  103. /**
  104. * Constructor.
  105. *
  106. * @param string $commandline The command line to run
  107. * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
  108. * @param array|null $env The environment variables or null to inherit
  109. * @param string|null $stdin The STDIN content
  110. * @param integer|float|null $timeout The timeout in seconds or null to disable
  111. * @param array $options An array of options for proc_open
  112. *
  113. * @throws RuntimeException When proc_open is not installed
  114. *
  115. * @api
  116. */
  117. public function __construct($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array())
  118. {
  119. if (!function_exists('proc_open')) {
  120. throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
  121. }
  122. $this->commandline = $commandline;
  123. $this->cwd = $cwd;
  124. // on windows, if the cwd changed via chdir(), proc_open defaults to the dir where php was started
  125. // on gnu/linux, PHP builds with --enable-maintainer-zts are also affected
  126. // @see : https://bugs.php.net/bug.php?id=51800
  127. // @see : https://bugs.php.net/bug.php?id=50524
  128. if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || defined('PHP_WINDOWS_VERSION_BUILD'))) {
  129. $this->cwd = getcwd();
  130. }
  131. if (null !== $env) {
  132. $this->setEnv($env);
  133. } else {
  134. $this->env = null;
  135. }
  136. $this->stdin = $stdin;
  137. $this->setTimeout($timeout);
  138. $this->useFileHandles = defined('PHP_WINDOWS_VERSION_BUILD');
  139. $this->enhanceWindowsCompatibility = true;
  140. $this->enhanceSigchildCompatibility = !defined('PHP_WINDOWS_VERSION_BUILD') && $this->isSigchildEnabled();
  141. $this->options = array_replace(array('suppress_errors' => true, 'binary_pipes' => true), $options);
  142. }
  143. public function __destruct()
  144. {
  145. // stop() will check if we have a process running.
  146. $this->stop();
  147. }
  148. public function __clone()
  149. {
  150. $this->resetProcessData();
  151. }
  152. /**
  153. * Runs the process.
  154. *
  155. * The callback receives the type of output (out or err) and
  156. * some bytes from the output in real-time. It allows to have feedback
  157. * from the independent process during execution.
  158. *
  159. * The STDOUT and STDERR are also available after the process is finished
  160. * via the getOutput() and getErrorOutput() methods.
  161. *
  162. * @param callback|null $callback A PHP callback to run whenever there is some
  163. * output available on STDOUT or STDERR
  164. *
  165. * @return integer The exit status code
  166. *
  167. * @throws RuntimeException When process can't be launch or is stopped
  168. *
  169. * @api
  170. */
  171. public function run($callback = null)
  172. {
  173. $this->start($callback);
  174. return $this->wait();
  175. }
  176. /**
  177. * Starts the process and returns after sending the STDIN.
  178. *
  179. * This method blocks until all STDIN data is sent to the process then it
  180. * returns while the process runs in the background.
  181. *
  182. * The termination of the process can be awaited with wait().
  183. *
  184. * The callback receives the type of output (out or err) and some bytes from
  185. * the output in real-time while writing the standard input to the process.
  186. * It allows to have feedback from the independent process during execution.
  187. * If there is no callback passed, the wait() method can be called
  188. * with true as a second parameter then the callback will get all data occurred
  189. * in (and since) the start call.
  190. *
  191. * @param callback|null $callback A PHP callback to run whenever there is some
  192. * output available on STDOUT or STDERR
  193. *
  194. * @throws RuntimeException When process can't be launch or is stopped
  195. * @throws RuntimeException When process is already running
  196. */
  197. public function start($callback = null)
  198. {
  199. if ($this->isRunning()) {
  200. throw new RuntimeException('Process is already running');
  201. }
  202. $this->resetProcessData();
  203. $this->starttime = microtime(true);
  204. $this->callback = $this->buildCallback($callback);
  205. $this->processPipes = new ProcessPipes($this->useFileHandles);
  206. $descriptors = $this->processPipes->getDescriptors();
  207. if (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  208. // last exit code is output on the fourth pipe and caught to work around --enable-sigchild
  209. $descriptors = array_merge($descriptors, array(array('pipe', 'w')));
  210. $this->commandline = '('.$this->commandline.') 3>/dev/null; code=$?; echo $code >&3; exit $code';
  211. }
  212. $commandline = $this->commandline;
  213. if (defined('PHP_WINDOWS_VERSION_BUILD') && $this->enhanceWindowsCompatibility) {
  214. $commandline = 'cmd /V:ON /E:ON /C "'.$commandline.'"';
  215. if (!isset($this->options['bypass_shell'])) {
  216. $this->options['bypass_shell'] = true;
  217. }
  218. }
  219. $this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $this->env, $this->options);
  220. if (!is_resource($this->process)) {
  221. throw new RuntimeException('Unable to launch a new process.');
  222. }
  223. $this->status = self::STATUS_STARTED;
  224. $this->processPipes->unblock();
  225. $this->processPipes->write(false, $this->stdin);
  226. $this->updateStatus(false);
  227. $this->checkTimeout();
  228. }
  229. /**
  230. * Restarts the process.
  231. *
  232. * Be warned that the process is cloned before being started.
  233. *
  234. * @param callable $callback A PHP callback to run whenever there is some
  235. * output available on STDOUT or STDERR
  236. *
  237. * @return Process The new process
  238. *
  239. * @throws RuntimeException When process can't be launch or is stopped
  240. * @throws RuntimeException When process is already running
  241. *
  242. * @see start()
  243. */
  244. public function restart($callback = null)
  245. {
  246. if ($this->isRunning()) {
  247. throw new RuntimeException('Process is already running');
  248. }
  249. $process = clone $this;
  250. $process->start($callback);
  251. return $process;
  252. }
  253. /**
  254. * Waits for the process to terminate.
  255. *
  256. * The callback receives the type of output (out or err) and some bytes
  257. * from the output in real-time while writing the standard input to the process.
  258. * It allows to have feedback from the independent process during execution.
  259. *
  260. * @param callback|null $callback A valid PHP callback
  261. *
  262. * @return integer The exitcode of the process
  263. *
  264. * @throws RuntimeException When process timed out
  265. * @throws RuntimeException When process stopped after receiving signal
  266. */
  267. public function wait($callback = null)
  268. {
  269. $this->updateStatus(false);
  270. if (null !== $callback) {
  271. $this->callback = $this->buildCallback($callback);
  272. }
  273. do {
  274. $this->checkTimeout();
  275. $running = defined('PHP_WINDOWS_VERSION_BUILD') ? $this->isRunning() : $this->processPipes->hasOpenHandles();
  276. $close = !defined('PHP_WINDOWS_VERSION_BUILD') || !$running;;
  277. $this->readPipes(true, $close);
  278. } while ($running);
  279. while ($this->isRunning()) {
  280. usleep(1000);
  281. }
  282. $this->processPipes->close();
  283. $exitcode = proc_close($this->process);
  284. if ($this->processInformation['signaled']) {
  285. if ($this->isSigchildEnabled()) {
  286. throw new RuntimeException('The process has been signaled.');
  287. }
  288. throw new RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig']));
  289. }
  290. $this->exitcode = $this->processInformation['running'] ? $exitcode : $this->processInformation['exitcode'];
  291. if (-1 == $this->exitcode && null !== $this->fallbackExitcode) {
  292. $this->exitcode = $this->fallbackExitcode;
  293. }
  294. return $this->exitcode;
  295. }
  296. /**
  297. * Returns the current output of the process (STDOUT).
  298. *
  299. * @return string The process output
  300. *
  301. * @api
  302. */
  303. public function getOutput()
  304. {
  305. $this->readPipes(false, defined('PHP_WINDOWS_VERSION_BUILD') ? !$this->processInformation['running'] : true);
  306. return $this->stdout;
  307. }
  308. /**
  309. * Returns the output incrementally.
  310. *
  311. * In comparison with the getOutput method which always return the whole
  312. * output, this one returns the new output since the last call.
  313. *
  314. * @return string The process output since the last call
  315. */
  316. public function getIncrementalOutput()
  317. {
  318. $data = $this->getOutput();
  319. $latest = substr($data, $this->incrementalOutputOffset);
  320. $this->incrementalOutputOffset = strlen($data);
  321. return $latest;
  322. }
  323. /**
  324. * Returns the current error output of the process (STDERR).
  325. *
  326. * @return string The process error output
  327. *
  328. * @api
  329. */
  330. public function getErrorOutput()
  331. {
  332. $this->readPipes(false, defined('PHP_WINDOWS_VERSION_BUILD') ? !$this->processInformation['running'] : true);
  333. return $this->stderr;
  334. }
  335. /**
  336. * Returns the errorOutput incrementally.
  337. *
  338. * In comparison with the getErrorOutput method which always return the
  339. * whole error output, this one returns the new error output since the last
  340. * call.
  341. *
  342. * @return string The process error output since the last call
  343. */
  344. public function getIncrementalErrorOutput()
  345. {
  346. $data = $this->getErrorOutput();
  347. $latest = substr($data, $this->incrementalErrorOutputOffset);
  348. $this->incrementalErrorOutputOffset = strlen($data);
  349. return $latest;
  350. }
  351. /**
  352. * Returns the exit code returned by the process.
  353. *
  354. * @return integer The exit status code
  355. *
  356. * @throws RuntimeException In case --enable-sigchild is activated and the sigchild compatibility mode is disabled
  357. *
  358. * @api
  359. */
  360. public function getExitCode()
  361. {
  362. if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
  363. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method');
  364. }
  365. $this->updateStatus(false);
  366. return $this->exitcode;
  367. }
  368. /**
  369. * Returns a string representation for the exit code returned by the process.
  370. *
  371. * This method relies on the Unix exit code status standardization
  372. * and might not be relevant for other operating systems.
  373. *
  374. * @return string A string representation for the exit status code
  375. *
  376. * @see http://tldp.org/LDP/abs/html/exitcodes.html
  377. * @see http://en.wikipedia.org/wiki/Unix_signal
  378. */
  379. public function getExitCodeText()
  380. {
  381. $exitcode = $this->getExitCode();
  382. return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
  383. }
  384. /**
  385. * Checks if the process ended successfully.
  386. *
  387. * @return Boolean true if the process ended successfully, false otherwise
  388. *
  389. * @api
  390. */
  391. public function isSuccessful()
  392. {
  393. return 0 === $this->getExitCode();
  394. }
  395. /**
  396. * Returns true if the child process has been terminated by an uncaught signal.
  397. *
  398. * It always returns false on Windows.
  399. *
  400. * @return Boolean
  401. *
  402. * @throws RuntimeException In case --enable-sigchild is activated
  403. *
  404. * @api
  405. */
  406. public function hasBeenSignaled()
  407. {
  408. if ($this->isSigchildEnabled()) {
  409. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved');
  410. }
  411. $this->updateStatus(false);
  412. return $this->processInformation['signaled'];
  413. }
  414. /**
  415. * Returns the number of the signal that caused the child process to terminate its execution.
  416. *
  417. * It is only meaningful if hasBeenSignaled() returns true.
  418. *
  419. * @return integer
  420. *
  421. * @throws RuntimeException In case --enable-sigchild is activated
  422. *
  423. * @api
  424. */
  425. public function getTermSignal()
  426. {
  427. if ($this->isSigchildEnabled()) {
  428. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved');
  429. }
  430. $this->updateStatus(false);
  431. return $this->processInformation['termsig'];
  432. }
  433. /**
  434. * Returns true if the child process has been stopped by a signal.
  435. *
  436. * It always returns false on Windows.
  437. *
  438. * @return Boolean
  439. *
  440. * @api
  441. */
  442. public function hasBeenStopped()
  443. {
  444. $this->updateStatus(false);
  445. return $this->processInformation['stopped'];
  446. }
  447. /**
  448. * Returns the number of the signal that caused the child process to stop its execution.
  449. *
  450. * It is only meaningful if hasBeenStopped() returns true.
  451. *
  452. * @return integer
  453. *
  454. * @api
  455. */
  456. public function getStopSignal()
  457. {
  458. $this->updateStatus(false);
  459. return $this->processInformation['stopsig'];
  460. }
  461. /**
  462. * Checks if the process is currently running.
  463. *
  464. * @return Boolean true if the process is currently running, false otherwise
  465. */
  466. public function isRunning()
  467. {
  468. if (self::STATUS_STARTED !== $this->status) {
  469. return false;
  470. }
  471. $this->updateStatus(false);
  472. return $this->processInformation['running'];
  473. }
  474. /**
  475. * Checks if the process has been started with no regard to the current state.
  476. *
  477. * @return Boolean true if status is ready, false otherwise
  478. */
  479. public function isStarted()
  480. {
  481. return $this->status != self::STATUS_READY;
  482. }
  483. /**
  484. * Checks if the process is terminated.
  485. *
  486. * @return Boolean true if process is terminated, false otherwise
  487. */
  488. public function isTerminated()
  489. {
  490. $this->updateStatus(false);
  491. return $this->status == self::STATUS_TERMINATED;
  492. }
  493. /**
  494. * Gets the process status.
  495. *
  496. * The status is one of: ready, started, terminated.
  497. *
  498. * @return string The current process status
  499. */
  500. public function getStatus()
  501. {
  502. $this->updateStatus(false);
  503. return $this->status;
  504. }
  505. /**
  506. * Stops the process.
  507. *
  508. * @param integer|float $timeout The timeout in seconds
  509. *
  510. * @return integer The exit-code of the process
  511. *
  512. * @throws RuntimeException if the process got signaled
  513. */
  514. public function stop($timeout = 10)
  515. {
  516. $timeoutMicro = microtime(true) + $timeout;
  517. if ($this->isRunning()) {
  518. proc_terminate($this->process);
  519. while ($this->isRunning() && microtime(true) < $timeoutMicro) {
  520. usleep(1000);
  521. }
  522. if (!defined('PHP_WINDOWS_VERSION_BUILD') && $this->isRunning()) {
  523. proc_terminate($this->process, SIGKILL);
  524. }
  525. $this->processPipes->close();
  526. $exitcode = proc_close($this->process);
  527. $this->exitcode = -1 === $this->processInformation['exitcode'] ? $exitcode : $this->processInformation['exitcode'];
  528. }
  529. $this->status = self::STATUS_TERMINATED;
  530. return $this->exitcode;
  531. }
  532. /**
  533. * Adds a line to the STDOUT stream.
  534. *
  535. * @param string $line The line to append
  536. */
  537. public function addOutput($line)
  538. {
  539. $this->stdout .= $line;
  540. }
  541. /**
  542. * Adds a line to the STDERR stream.
  543. *
  544. * @param string $line The line to append
  545. */
  546. public function addErrorOutput($line)
  547. {
  548. $this->stderr .= $line;
  549. }
  550. /**
  551. * Gets the command line to be executed.
  552. *
  553. * @return string The command to execute
  554. */
  555. public function getCommandLine()
  556. {
  557. return $this->commandline;
  558. }
  559. /**
  560. * Sets the command line to be executed.
  561. *
  562. * @param string $commandline The command to execute
  563. *
  564. * @return self The current Process instance
  565. */
  566. public function setCommandLine($commandline)
  567. {
  568. $this->commandline = $commandline;
  569. return $this;
  570. }
  571. /**
  572. * Gets the process timeout.
  573. *
  574. * @return float|null The timeout in seconds or null if it's disabled
  575. */
  576. public function getTimeout()
  577. {
  578. return $this->timeout;
  579. }
  580. /**
  581. * Sets the process timeout.
  582. *
  583. * To disable the timeout, set this value to null.
  584. *
  585. * @param integer|float|null $timeout The timeout in seconds
  586. *
  587. * @return self The current Process instance
  588. *
  589. * @throws InvalidArgumentException if the timeout is negative
  590. */
  591. public function setTimeout($timeout)
  592. {
  593. $timeout = (float) $timeout;
  594. if (0.0 === $timeout) {
  595. $timeout = null;
  596. } elseif ($timeout < 0) {
  597. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  598. }
  599. $this->timeout = $timeout;
  600. return $this;
  601. }
  602. /**
  603. * Gets the working directory.
  604. *
  605. * @return string|null The current working directory or null on failure
  606. */
  607. public function getWorkingDirectory()
  608. {
  609. if (null === $this->cwd) {
  610. // getcwd() will return false if any one of the parent directories does not have
  611. // the readable or search mode set, even if the current directory does
  612. return getcwd() ?: null;
  613. }
  614. return $this->cwd;
  615. }
  616. /**
  617. * Sets the current working directory.
  618. *
  619. * @param string $cwd The new working directory
  620. *
  621. * @return self The current Process instance
  622. */
  623. public function setWorkingDirectory($cwd)
  624. {
  625. $this->cwd = $cwd;
  626. return $this;
  627. }
  628. /**
  629. * Gets the environment variables.
  630. *
  631. * @return array The current environment variables
  632. */
  633. public function getEnv()
  634. {
  635. return $this->env;
  636. }
  637. /**
  638. * Sets the environment variables.
  639. *
  640. * An environment variable value should be a string.
  641. * If it is an array, the variable is ignored.
  642. *
  643. * That happens in PHP when 'argv' is registered into
  644. * the $_ENV array for instance.
  645. *
  646. * @param array $env The new environment variables
  647. *
  648. * @return self The current Process instance
  649. */
  650. public function setEnv(array $env)
  651. {
  652. // Process can not handle env values that are arrays
  653. $env = array_filter($env, function ($value) { if (!is_array($value)) { return true; } });
  654. $this->env = array();
  655. foreach ($env as $key => $value) {
  656. $this->env[(binary) $key] = (binary) $value;
  657. }
  658. return $this;
  659. }
  660. /**
  661. * Gets the contents of STDIN.
  662. *
  663. * @return string|null The current contents
  664. */
  665. public function getStdin()
  666. {
  667. return $this->stdin;
  668. }
  669. /**
  670. * Sets the contents of STDIN.
  671. *
  672. * @param string|null $stdin The new contents
  673. *
  674. * @return self The current Process instance
  675. */
  676. public function setStdin($stdin)
  677. {
  678. $this->stdin = $stdin;
  679. return $this;
  680. }
  681. /**
  682. * Gets the options for proc_open.
  683. *
  684. * @return array The current options
  685. */
  686. public function getOptions()
  687. {
  688. return $this->options;
  689. }
  690. /**
  691. * Sets the options for proc_open.
  692. *
  693. * @param array $options The new options
  694. *
  695. * @return self The current Process instance
  696. */
  697. public function setOptions(array $options)
  698. {
  699. $this->options = $options;
  700. return $this;
  701. }
  702. /**
  703. * Gets whether or not Windows compatibility is enabled
  704. *
  705. * This is true by default.
  706. *
  707. * @return Boolean
  708. */
  709. public function getEnhanceWindowsCompatibility()
  710. {
  711. return $this->enhanceWindowsCompatibility;
  712. }
  713. /**
  714. * Sets whether or not Windows compatibility is enabled
  715. *
  716. * @param Boolean $enhance
  717. *
  718. * @return self The current Process instance
  719. */
  720. public function setEnhanceWindowsCompatibility($enhance)
  721. {
  722. $this->enhanceWindowsCompatibility = (Boolean) $enhance;
  723. return $this;
  724. }
  725. /**
  726. * Return whether sigchild compatibility mode is activated or not
  727. *
  728. * @return Boolean
  729. */
  730. public function getEnhanceSigchildCompatibility()
  731. {
  732. return $this->enhanceSigchildCompatibility;
  733. }
  734. /**
  735. * Activate sigchild compatibility mode
  736. *
  737. * Sigchild compatibility mode is required to get the exit code and
  738. * determine the success of a process when PHP has been compiled with
  739. * the --enable-sigchild option
  740. *
  741. * @param Boolean $enhance
  742. *
  743. * @return self The current Process instance
  744. */
  745. public function setEnhanceSigchildCompatibility($enhance)
  746. {
  747. $this->enhanceSigchildCompatibility = (Boolean) $enhance;
  748. return $this;
  749. }
  750. /**
  751. * Performs a check between the timeout definition and the time the process
  752. * started
  753. *
  754. * In case you run a background process (with the start method), you should
  755. * trigger this method regularly to ensure the process timeout
  756. *
  757. * @throws RuntimeException In case the timeout was reached
  758. */
  759. public function checkTimeout()
  760. {
  761. if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
  762. $this->stop(0);
  763. throw new RuntimeException('The process timed-out.');
  764. }
  765. }
  766. /**
  767. * Builds up the callback used by wait().
  768. *
  769. * The callbacks adds all occurred output to the specific buffer and calls
  770. * the user callback (if present) with the received output.
  771. *
  772. * @param callback|null $callback The user defined PHP callback
  773. *
  774. * @return callback A PHP callable
  775. */
  776. protected function buildCallback($callback)
  777. {
  778. $that = $this;
  779. $out = self::OUT;
  780. $err = self::ERR;
  781. $callback = function ($type, $data) use ($that, $callback, $out, $err) {
  782. if ($out == $type) {
  783. $that->addOutput($data);
  784. } else {
  785. $that->addErrorOutput($data);
  786. }
  787. if (null !== $callback) {
  788. call_user_func($callback, $type, $data);
  789. }
  790. };
  791. return $callback;
  792. }
  793. /**
  794. * Updates the status of the process, reads pipes.
  795. *
  796. * @param Boolean $blocking Whether to use a clocking read call.
  797. */
  798. protected function updateStatus($blocking)
  799. {
  800. if (self::STATUS_STARTED !== $this->status) {
  801. return;
  802. }
  803. $this->processInformation = proc_get_status($this->process);
  804. $this->readPipes($blocking, defined('PHP_WINDOWS_VERSION_BUILD') ? !$this->processInformation['running'] : true);
  805. if (!$this->processInformation['running']) {
  806. $this->status = self::STATUS_TERMINATED;
  807. if (-1 !== $this->processInformation['exitcode']) {
  808. $this->exitcode = $this->processInformation['exitcode'];
  809. }
  810. }
  811. }
  812. /**
  813. * Return whether PHP has been compiled with the '--enable-sigchild' option or not
  814. *
  815. * @return Boolean
  816. */
  817. protected function isSigchildEnabled()
  818. {
  819. if (null !== self::$sigchild) {
  820. return self::$sigchild;
  821. }
  822. ob_start();
  823. phpinfo(INFO_GENERAL);
  824. return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  825. }
  826. /**
  827. * Reads pipes, executes callback.
  828. *
  829. * @param Boolean $blocking Whether to use blocking calls or not.
  830. */
  831. private function readPipes($blocking, $close)
  832. {
  833. if ($close) {
  834. $result = $this->processPipes->readAndCloseHandles($blocking);
  835. } else {
  836. $result = $this->processPipes->read($blocking);
  837. }
  838. foreach ($result as $type => $data) {
  839. if (3 == $type) {
  840. $this->fallbackExitcode = (int) $data;
  841. } else {
  842. call_user_func($this->callback, $type === self::STDOUT ? self::OUT : self::ERR, $data);
  843. }
  844. }
  845. }
  846. /**
  847. * Resets data related to the latest run of the process.
  848. */
  849. private function resetProcessData()
  850. {
  851. $this->starttime = null;
  852. $this->callback = null;
  853. $this->exitcode = null;
  854. $this->fallbackExitcode = null;
  855. $this->processInformation = null;
  856. $this->stdout = null;
  857. $this->stderr = null;
  858. $this->process = null;
  859. $this->status = self::STATUS_READY;
  860. $this->incrementalOutputOffset = 0;
  861. $this->incrementalErrorOutputOffset = 0;
  862. }
  863. }