Process.php 31 KB

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