Process.php 29 KB

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