Process.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  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 $pipes;
  50. private $process;
  51. private $status = self::STATUS_READY;
  52. private $incrementalOutputOffset;
  53. private $incrementalErrorOutputOffset;
  54. private $tty;
  55. private $fileHandles;
  56. private $readBytes;
  57. private static $sigchild;
  58. /**
  59. * Exit codes translation table.
  60. *
  61. * User-defined errors must use exit codes in the 64-113 range.
  62. *
  63. * @var array
  64. */
  65. public static $exitCodes = array(
  66. 0 => 'OK',
  67. 1 => 'General error',
  68. 2 => 'Misuse of shell builtins',
  69. 126 => 'Invoked command cannot execute',
  70. 127 => 'Command not found',
  71. 128 => 'Invalid exit argument',
  72. // signals
  73. 129 => 'Hangup',
  74. 130 => 'Interrupt',
  75. 131 => 'Quit and dump core',
  76. 132 => 'Illegal instruction',
  77. 133 => 'Trace/breakpoint trap',
  78. 134 => 'Process aborted',
  79. 135 => 'Bus error: "access to undefined portion of memory object"',
  80. 136 => 'Floating point exception: "erroneous arithmetic operation"',
  81. 137 => 'Kill (terminate immediately)',
  82. 138 => 'User-defined 1',
  83. 139 => 'Segmentation violation',
  84. 140 => 'User-defined 2',
  85. 141 => 'Write to pipe with no one reading',
  86. 142 => 'Signal raised by alarm',
  87. 143 => 'Termination (request to terminate)',
  88. // 144 - not defined
  89. 145 => 'Child process terminated, stopped (or continued*)',
  90. 146 => 'Continue if stopped',
  91. 147 => 'Stop executing temporarily',
  92. 148 => 'Terminal stop signal',
  93. 149 => 'Background process attempting to read from tty ("in")',
  94. 150 => 'Background process attempting to write to tty ("out")',
  95. 151 => 'Urgent data available on socket',
  96. 152 => 'CPU time limit exceeded',
  97. 153 => 'File size limit exceeded',
  98. 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
  99. 155 => 'Profiling timer expired',
  100. // 156 - not defined
  101. 157 => 'Pollable event',
  102. // 158 - not defined
  103. 159 => 'Bad syscall',
  104. );
  105. /**
  106. * Constructor.
  107. *
  108. * @param string $commandline The command line to run
  109. * @param string $cwd The working directory
  110. * @param array $env The environment variables or null to inherit
  111. * @param string $stdin The STDIN content
  112. * @param integer $timeout The timeout in seconds
  113. * @param array $options An array of options for proc_open
  114. *
  115. * @throws RuntimeException When proc_open is not installed
  116. *
  117. * @api
  118. */
  119. public function __construct($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array())
  120. {
  121. if (!function_exists('proc_open')) {
  122. throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
  123. }
  124. $this->commandline = $commandline;
  125. $this->cwd = $cwd;
  126. // on windows, if the cwd changed via chdir(), proc_open defaults to the dir where php was started
  127. // on gnu/linux, PHP builds with --enable-maintainer-zts are also affected
  128. // @see : https://bugs.php.net/bug.php?id=51800
  129. // @see : https://bugs.php.net/bug.php?id=50524
  130. if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || defined('PHP_WINDOWS_VERSION_BUILD'))) {
  131. $this->cwd = getcwd();
  132. }
  133. if (null !== $env) {
  134. $this->setEnv($env);
  135. } else {
  136. $this->env = null;
  137. }
  138. $this->stdin = $stdin;
  139. $this->setTimeout($timeout);
  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->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. foreach ($this->pipes as $pipe) {
  220. stream_set_blocking($pipe, false);
  221. }
  222. $this->writePipes();
  223. $this->updateStatus(false);
  224. $this->checkTimeout();
  225. }
  226. /**
  227. * Restarts the process.
  228. *
  229. * Be warned that the process is cloned before being started.
  230. *
  231. * @param callable $callback A PHP callback to run whenever there is some
  232. * output available on STDOUT or STDERR
  233. *
  234. * @return Process The new process
  235. *
  236. * @throws RuntimeException When process can't be launch or is stopped
  237. * @throws RuntimeException When process is already running
  238. *
  239. * @see start()
  240. */
  241. public function restart($callback = null)
  242. {
  243. if ($this->isRunning()) {
  244. throw new RuntimeException('Process is already running');
  245. }
  246. $process = clone $this;
  247. $process->start($callback);
  248. return $process;
  249. }
  250. /**
  251. * Waits for the process to terminate.
  252. *
  253. * The callback receives the type of output (out or err) and some bytes
  254. * from the output in real-time while writing the standard input to the process.
  255. * It allows to have feedback from the independent process during execution.
  256. *
  257. * @param callback|null $callback A valid PHP callback
  258. *
  259. * @return integer The exitcode of the process
  260. *
  261. * @throws RuntimeException When process timed out
  262. * @throws RuntimeException When process stopped after receiving signal
  263. */
  264. public function wait($callback = null)
  265. {
  266. $this->updateStatus(false);
  267. if (null !== $callback) {
  268. $this->callback = $this->buildCallback($callback);
  269. }
  270. while ($this->pipes || (defined('PHP_WINDOWS_VERSION_BUILD') && $this->fileHandles)) {
  271. $this->checkTimeout();
  272. $this->readPipes(true);
  273. }
  274. $this->updateStatus(false);
  275. if ($this->processInformation['signaled']) {
  276. if ($this->isSigchildEnabled()) {
  277. throw new RuntimeException('The process has been signaled.');
  278. }
  279. throw new RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig']));
  280. }
  281. $time = 0;
  282. while ($this->isRunning() && $time < 1000000) {
  283. $time += 1000;
  284. usleep(1000);
  285. }
  286. if ($this->processInformation['signaled']) {
  287. if ($this->isSigchildEnabled()) {
  288. throw new RuntimeException('The process has been signaled.');
  289. }
  290. throw new RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig']));
  291. }
  292. return $this->exitcode;
  293. }
  294. /**
  295. * Returns the Pid (process identifier), if applicable.
  296. *
  297. * @return integer|null The process id if running, null otherwise
  298. *
  299. * @throws RuntimeException In case --enable-sigchild is activated
  300. */
  301. public function getPid()
  302. {
  303. if ($this->isSigchildEnabled()) {
  304. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved.');
  305. }
  306. $this->updateStatus(false);
  307. return $this->isRunning() ? $this->processInformation['pid'] : null;
  308. }
  309. /**
  310. * Sends a posix signal to the process.
  311. *
  312. * @param integer $signal A valid posix signal (see http://www.php.net/manual/en/pcntl.constants.php)
  313. * @return Process
  314. *
  315. * @throws LogicException In case the process is not running
  316. * @throws RuntimeException In case --enable-sigchild is activated
  317. * @throws RuntimeException In case of failure
  318. */
  319. public function signal($signal)
  320. {
  321. if (!$this->isRunning()) {
  322. throw new LogicException('Can not send signal on a non running process.');
  323. }
  324. if ($this->isSigchildEnabled()) {
  325. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. The process can not be signaled.');
  326. }
  327. if (true !== @proc_terminate($this->process, $signal)) {
  328. throw new RuntimeException(sprintf('Error while sending signal `%d`.', $signal));
  329. }
  330. return $this;
  331. }
  332. /**
  333. * Returns the current output of the process (STDOUT).
  334. *
  335. * @return string The process output
  336. *
  337. * @api
  338. */
  339. public function getOutput()
  340. {
  341. $this->readPipes(false);
  342. return $this->stdout;
  343. }
  344. /**
  345. * Returns the output incrementally.
  346. *
  347. * In comparison with the getOutput method which always return the whole
  348. * output, this one returns the new output since the last call.
  349. *
  350. * @return string The process output since the last call
  351. */
  352. public function getIncrementalOutput()
  353. {
  354. $data = $this->getOutput();
  355. $latest = substr($data, $this->incrementalOutputOffset);
  356. $this->incrementalOutputOffset = strlen($data);
  357. return $latest;
  358. }
  359. /**
  360. * Returns the current error output of the process (STDERR).
  361. *
  362. * @return string The process error output
  363. *
  364. * @api
  365. */
  366. public function getErrorOutput()
  367. {
  368. $this->readPipes(false);
  369. return $this->stderr;
  370. }
  371. /**
  372. * Returns the errorOutput incrementally.
  373. *
  374. * In comparison with the getErrorOutput method which always return the
  375. * whole error output, this one returns the new error output since the last
  376. * call.
  377. *
  378. * @return string The process error output since the last call
  379. */
  380. public function getIncrementalErrorOutput()
  381. {
  382. $data = $this->getErrorOutput();
  383. $latest = substr($data, $this->incrementalErrorOutputOffset);
  384. $this->incrementalErrorOutputOffset = strlen($data);
  385. return $latest;
  386. }
  387. /**
  388. * Returns the exit code returned by the process.
  389. *
  390. * @return integer The exit status code
  391. *
  392. * @throws RuntimeException In case --enable-sigchild is activated and the sigchild compatibility mode is disabled
  393. *
  394. * @api
  395. */
  396. public function getExitCode()
  397. {
  398. if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
  399. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method');
  400. }
  401. $this->updateStatus(false);
  402. return $this->exitcode;
  403. }
  404. /**
  405. * Returns a string representation for the exit code returned by the process.
  406. *
  407. * This method relies on the Unix exit code status standardization
  408. * and might not be relevant for other operating systems.
  409. *
  410. * @return string A string representation for the exit status code
  411. *
  412. * @see http://tldp.org/LDP/abs/html/exitcodes.html
  413. * @see http://en.wikipedia.org/wiki/Unix_signal
  414. */
  415. public function getExitCodeText()
  416. {
  417. $exitcode = $this->getExitCode();
  418. return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
  419. }
  420. /**
  421. * Checks if the process ended successfully.
  422. *
  423. * @return Boolean true if the process ended successfully, false otherwise
  424. *
  425. * @api
  426. */
  427. public function isSuccessful()
  428. {
  429. return 0 === $this->getExitCode();
  430. }
  431. /**
  432. * Returns true if the child process has been terminated by an uncaught signal.
  433. *
  434. * It always returns false on Windows.
  435. *
  436. * @return Boolean
  437. *
  438. * @throws RuntimeException In case --enable-sigchild is activated
  439. *
  440. * @api
  441. */
  442. public function hasBeenSignaled()
  443. {
  444. if ($this->isSigchildEnabled()) {
  445. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved');
  446. }
  447. $this->updateStatus(false);
  448. return $this->processInformation['signaled'];
  449. }
  450. /**
  451. * Returns the number of the signal that caused the child process to terminate its execution.
  452. *
  453. * It is only meaningful if hasBeenSignaled() returns true.
  454. *
  455. * @return integer
  456. *
  457. * @throws RuntimeException In case --enable-sigchild is activated
  458. *
  459. * @api
  460. */
  461. public function getTermSignal()
  462. {
  463. if ($this->isSigchildEnabled()) {
  464. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved');
  465. }
  466. $this->updateStatus(false);
  467. return $this->processInformation['termsig'];
  468. }
  469. /**
  470. * Returns true if the child process has been stopped by a signal.
  471. *
  472. * It always returns false on Windows.
  473. *
  474. * @return Boolean
  475. *
  476. * @api
  477. */
  478. public function hasBeenStopped()
  479. {
  480. $this->updateStatus(false);
  481. return $this->processInformation['stopped'];
  482. }
  483. /**
  484. * Returns the number of the signal that caused the child process to stop its execution.
  485. *
  486. * It is only meaningful if hasBeenStopped() returns true.
  487. *
  488. * @return integer
  489. *
  490. * @api
  491. */
  492. public function getStopSignal()
  493. {
  494. $this->updateStatus(false);
  495. return $this->processInformation['stopsig'];
  496. }
  497. /**
  498. * Checks if the process is currently running.
  499. *
  500. * @return Boolean true if the process is currently running, false otherwise
  501. */
  502. public function isRunning()
  503. {
  504. if (self::STATUS_STARTED !== $this->status) {
  505. return false;
  506. }
  507. $this->updateStatus(false);
  508. return $this->processInformation['running'];
  509. }
  510. /**
  511. * Checks if the process has been started with no regard to the current state.
  512. *
  513. * @return Boolean true if status is ready, false otherwise
  514. */
  515. public function isStarted()
  516. {
  517. return $this->status != self::STATUS_READY;
  518. }
  519. /**
  520. * Checks if the process is terminated.
  521. *
  522. * @return Boolean true if process is terminated, false otherwise
  523. */
  524. public function isTerminated()
  525. {
  526. $this->updateStatus(false);
  527. return $this->status == self::STATUS_TERMINATED;
  528. }
  529. /**
  530. * Gets the process status.
  531. *
  532. * The status is one of: ready, started, terminated.
  533. *
  534. * @return string The current process status
  535. */
  536. public function getStatus()
  537. {
  538. $this->updateStatus(false);
  539. return $this->status;
  540. }
  541. /**
  542. * Stops the process.
  543. *
  544. * @param integer|float $timeout The timeout in seconds
  545. * @param integer $signal A posix signal to send in case the process has not stop at timeout, default is SIGKILL
  546. *
  547. * @return integer The exit-code of the process
  548. *
  549. * @throws RuntimeException if the process got signaled
  550. */
  551. public function stop($timeout = 10, $signal = null)
  552. {
  553. $timeoutMicro = microtime(true) + $timeout;
  554. if ($this->isRunning()) {
  555. proc_terminate($this->process);
  556. do {
  557. usleep(1000);
  558. } while ($this->isRunning() && microtime(true) < $timeoutMicro);
  559. if ($this->isRunning() && !$this->isSigchildEnabled()) {
  560. if (null !== $signal || defined('SIGKILL')) {
  561. $this->signal($signal ?: SIGKILL);
  562. }
  563. }
  564. $this->updateStatus(false);
  565. }
  566. $this->status = self::STATUS_TERMINATED;
  567. return $this->exitcode;
  568. }
  569. /**
  570. * Adds a line to the STDOUT stream.
  571. *
  572. * @param string $line The line to append
  573. */
  574. public function addOutput($line)
  575. {
  576. $this->stdout .= $line;
  577. }
  578. /**
  579. * Adds a line to the STDERR stream.
  580. *
  581. * @param string $line The line to append
  582. */
  583. public function addErrorOutput($line)
  584. {
  585. $this->stderr .= $line;
  586. }
  587. /**
  588. * Gets the command line to be executed.
  589. *
  590. * @return string The command to execute
  591. */
  592. public function getCommandLine()
  593. {
  594. return $this->commandline;
  595. }
  596. /**
  597. * Sets the command line to be executed.
  598. *
  599. * @param string $commandline The command to execute
  600. *
  601. * @return self The current Process instance
  602. */
  603. public function setCommandLine($commandline)
  604. {
  605. $this->commandline = $commandline;
  606. return $this;
  607. }
  608. /**
  609. * Gets the process timeout.
  610. *
  611. * @return integer|null The timeout in seconds or null if it's disabled
  612. */
  613. public function getTimeout()
  614. {
  615. return $this->timeout;
  616. }
  617. /**
  618. * Sets the process timeout.
  619. *
  620. * To disable the timeout, set this value to null.
  621. *
  622. * @param float|null $timeout The timeout in seconds
  623. *
  624. * @return self The current Process instance
  625. *
  626. * @throws InvalidArgumentException if the timeout is negative
  627. */
  628. public function setTimeout($timeout)
  629. {
  630. if (null === $timeout) {
  631. $this->timeout = null;
  632. return $this;
  633. }
  634. $timeout = (float) $timeout;
  635. if ($timeout < 0) {
  636. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  637. }
  638. $this->timeout = $timeout;
  639. return $this;
  640. }
  641. /**
  642. * Enables or disables the TTY mode.
  643. *
  644. * @param boolean $tty True to enabled and false to disable
  645. *
  646. * @return self The current Process instance
  647. */
  648. public function setTty($tty)
  649. {
  650. $this->tty = (Boolean) $tty;
  651. return $this;
  652. }
  653. /**
  654. * Checks if the TTY mode is enabled.
  655. *
  656. * @return Boolean true if the TTY mode is enabled, false otherwise
  657. */
  658. public function isTty()
  659. {
  660. return $this->tty;
  661. }
  662. /**
  663. * Gets the working directory.
  664. *
  665. * @return string The current working directory
  666. */
  667. public function getWorkingDirectory()
  668. {
  669. // This is for BC only
  670. if (null === $this->cwd) {
  671. // getcwd() will return false if any one of the parent directories does not have
  672. // the readable or search mode set, even if the current directory does
  673. return getcwd() ?: null;
  674. }
  675. return $this->cwd;
  676. }
  677. /**
  678. * Sets the current working directory.
  679. *
  680. * @param string $cwd The new working directory
  681. *
  682. * @return self The current Process instance
  683. */
  684. public function setWorkingDirectory($cwd)
  685. {
  686. $this->cwd = $cwd;
  687. return $this;
  688. }
  689. /**
  690. * Gets the environment variables.
  691. *
  692. * @return array The current environment variables
  693. */
  694. public function getEnv()
  695. {
  696. return $this->env;
  697. }
  698. /**
  699. * Sets the environment variables.
  700. *
  701. * An environment variable value should be a string.
  702. * If it is an array, the variable is ignored.
  703. *
  704. * That happens in PHP when 'argv' is registered into
  705. * the $_ENV array for instance.
  706. *
  707. * @param array $env The new environment variables
  708. *
  709. * @return self The current Process instance
  710. */
  711. public function setEnv(array $env)
  712. {
  713. // Process can not handle env values that are arrays
  714. $env = array_filter($env, function ($value) { if (!is_array($value)) { return true; } });
  715. $this->env = array();
  716. foreach ($env as $key => $value) {
  717. $this->env[(binary) $key] = (binary) $value;
  718. }
  719. return $this;
  720. }
  721. /**
  722. * Gets the contents of STDIN.
  723. *
  724. * @return string The current contents
  725. */
  726. public function getStdin()
  727. {
  728. return $this->stdin;
  729. }
  730. /**
  731. * Sets the contents of STDIN.
  732. *
  733. * @param string $stdin The new contents
  734. *
  735. * @return self The current Process instance
  736. */
  737. public function setStdin($stdin)
  738. {
  739. $this->stdin = $stdin;
  740. return $this;
  741. }
  742. /**
  743. * Gets the options for proc_open.
  744. *
  745. * @return array The current options
  746. */
  747. public function getOptions()
  748. {
  749. return $this->options;
  750. }
  751. /**
  752. * Sets the options for proc_open.
  753. *
  754. * @param array $options The new options
  755. *
  756. * @return self The current Process instance
  757. */
  758. public function setOptions(array $options)
  759. {
  760. $this->options = $options;
  761. return $this;
  762. }
  763. /**
  764. * Gets whether or not Windows compatibility is enabled.
  765. *
  766. * This is true by default.
  767. *
  768. * @return Boolean
  769. */
  770. public function getEnhanceWindowsCompatibility()
  771. {
  772. return $this->enhanceWindowsCompatibility;
  773. }
  774. /**
  775. * Sets whether or not Windows compatibility is enabled.
  776. *
  777. * @param Boolean $enhance
  778. *
  779. * @return self The current Process instance
  780. */
  781. public function setEnhanceWindowsCompatibility($enhance)
  782. {
  783. $this->enhanceWindowsCompatibility = (Boolean) $enhance;
  784. return $this;
  785. }
  786. /**
  787. * Returns whether sigchild compatibility mode is activated or not.
  788. *
  789. * @return Boolean
  790. */
  791. public function getEnhanceSigchildCompatibility()
  792. {
  793. return $this->enhanceSigchildCompatibility;
  794. }
  795. /**
  796. * Activates sigchild compatibility mode.
  797. *
  798. * Sigchild compatibility mode is required to get the exit code and
  799. * determine the success of a process when PHP has been compiled with
  800. * the --enable-sigchild option
  801. *
  802. * @param Boolean $enhance
  803. *
  804. * @return self The current Process instance
  805. */
  806. public function setEnhanceSigchildCompatibility($enhance)
  807. {
  808. $this->enhanceSigchildCompatibility = (Boolean) $enhance;
  809. return $this;
  810. }
  811. /**
  812. * Performs a check between the timeout definition and the time the process started.
  813. *
  814. * In case you run a background process (with the start method), you should
  815. * trigger this method regularly to ensure the process timeout
  816. *
  817. * @throws RuntimeException In case the timeout was reached
  818. */
  819. public function checkTimeout()
  820. {
  821. if (0 < $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
  822. $this->stop(0);
  823. throw new RuntimeException('The process timed-out.');
  824. }
  825. }
  826. /**
  827. * Creates the descriptors needed by the proc_open.
  828. *
  829. * @return array
  830. */
  831. private function getDescriptors()
  832. {
  833. //Fix for PHP bug #51800: reading from STDOUT pipe hangs forever on Windows if the output is too big.
  834. //Workaround for this problem is to use temporary files instead of pipes on Windows platform.
  835. //@see https://bugs.php.net/bug.php?id=51800
  836. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  837. $this->fileHandles = array(
  838. self::STDOUT => tmpfile(),
  839. );
  840. if (false === $this->fileHandles[self::STDOUT]) {
  841. throw new RuntimeException('A temporary file could not be opened to write the process output to, verify that your TEMP environment variable is writable');
  842. }
  843. $this->readBytes = array(
  844. self::STDOUT => 0,
  845. );
  846. return array(array('pipe', 'r'), $this->fileHandles[self::STDOUT], array('pipe', 'w'));
  847. }
  848. if ($this->tty) {
  849. $descriptors = array(
  850. array('file', '/dev/tty', 'r'),
  851. array('file', '/dev/tty', 'w'),
  852. array('file', '/dev/tty', 'w'),
  853. );
  854. } else {
  855. $descriptors = array(
  856. array('pipe', 'r'), // stdin
  857. array('pipe', 'w'), // stdout
  858. array('pipe', 'w'), // stderr
  859. );
  860. }
  861. if ($this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  862. // last exit code is output on the fourth pipe and caught to work around --enable-sigchild
  863. $descriptors = array_merge($descriptors, array(array('pipe', 'w')));
  864. $this->commandline = '('.$this->commandline.') 3>/dev/null; code=$?; echo $code >&3; exit $code';
  865. }
  866. return $descriptors;
  867. }
  868. /**
  869. * Builds up the callback used by wait().
  870. *
  871. * The callbacks adds all occurred output to the specific buffer and calls
  872. * the user callback (if present) with the received output.
  873. *
  874. * @param callback|null $callback The user defined PHP callback
  875. *
  876. * @return callback A PHP callable
  877. */
  878. protected function buildCallback($callback)
  879. {
  880. $that = $this;
  881. $out = self::OUT;
  882. $err = self::ERR;
  883. $callback = function ($type, $data) use ($that, $callback, $out, $err) {
  884. if ($out == $type) {
  885. $that->addOutput($data);
  886. } else {
  887. $that->addErrorOutput($data);
  888. }
  889. if (null !== $callback) {
  890. call_user_func($callback, $type, $data);
  891. }
  892. };
  893. return $callback;
  894. }
  895. /**
  896. * Updates the status of the process, reads pipes.
  897. *
  898. * @param Boolean $blocking Whether to use a clocking read call.
  899. */
  900. protected function updateStatus($blocking)
  901. {
  902. if (self::STATUS_STARTED !== $this->status) {
  903. return;
  904. }
  905. $this->readPipes($blocking);
  906. $this->processInformation = proc_get_status($this->process);
  907. $this->captureExitCode();
  908. if (!$this->processInformation['running']) {
  909. $this->close();
  910. $this->status = self::STATUS_TERMINATED;
  911. }
  912. }
  913. /**
  914. * Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
  915. *
  916. * @return Boolean
  917. */
  918. protected function isSigchildEnabled()
  919. {
  920. if (null !== self::$sigchild) {
  921. return self::$sigchild;
  922. }
  923. ob_start();
  924. phpinfo(INFO_GENERAL);
  925. return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  926. }
  927. /**
  928. * Handles the windows file handles fallbacks.
  929. *
  930. * @param Boolean $closeEmptyHandles if true, handles that are empty will be assumed closed
  931. */
  932. private function processFileHandles($closeEmptyHandles = false)
  933. {
  934. $fh = $this->fileHandles;
  935. foreach ($fh as $type => $fileHandle) {
  936. fseek($fileHandle, $this->readBytes[$type]);
  937. $data = fread($fileHandle, 8192);
  938. if (strlen($data) > 0) {
  939. $this->readBytes[$type] += strlen($data);
  940. call_user_func($this->callback, $type == 1 ? self::OUT : self::ERR, $data);
  941. }
  942. if (false === $data || ($closeEmptyHandles && '' === $data && feof($fileHandle))) {
  943. fclose($fileHandle);
  944. unset($this->fileHandles[$type]);
  945. }
  946. }
  947. }
  948. /**
  949. * Returns true if a system call has been interrupted.
  950. *
  951. * @return Boolean
  952. */
  953. private function hasSystemCallBeenInterrupted()
  954. {
  955. $lastError = error_get_last();
  956. // stream_select returns false when the `select` system call is interrupted by an incoming signal
  957. return isset($lastError['message']) && false !== stripos($lastError['message'], 'interrupted system call');
  958. }
  959. /**
  960. * Reads pipes, executes callback.
  961. *
  962. * @param Boolean $blocking Whether to use blocking calls or not.
  963. */
  964. private function readPipes($blocking)
  965. {
  966. if (defined('PHP_WINDOWS_VERSION_BUILD') && $this->fileHandles) {
  967. $this->processFileHandles(!$this->pipes);
  968. }
  969. if ($this->pipes) {
  970. $r = $this->pipes;
  971. $w = null;
  972. $e = null;
  973. // let's have a look if something changed in streams
  974. if (false === $n = @stream_select($r, $w, $e, 0, $blocking ? ceil(self::TIMEOUT_PRECISION * 1E6) : 0)) {
  975. // if a system call has been interrupted, forget about it, let's try again
  976. // otherwise, an error occured, let's reset pipes
  977. if (!$this->hasSystemCallBeenInterrupted()) {
  978. $this->pipes = array();
  979. }
  980. return;
  981. }
  982. // nothing has changed
  983. if (0 === $n) {
  984. return;
  985. }
  986. $this->processReadPipes($r);
  987. }
  988. }
  989. /**
  990. * Writes data to pipes.
  991. *
  992. * @param Boolean $blocking Whether to use blocking calls or not.
  993. */
  994. private function writePipes()
  995. {
  996. if ($this->tty) {
  997. $this->status = self::STATUS_TERMINATED;
  998. return;
  999. }
  1000. if (null === $this->stdin) {
  1001. fclose($this->pipes[0]);
  1002. unset($this->pipes[0]);
  1003. return;
  1004. }
  1005. $writePipes = array($this->pipes[0]);
  1006. unset($this->pipes[0]);
  1007. $stdinLen = strlen($this->stdin);
  1008. $stdinOffset = 0;
  1009. while ($writePipes) {
  1010. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  1011. $this->processFileHandles();
  1012. }
  1013. $r = $this->pipes;
  1014. $w = $writePipes;
  1015. $e = null;
  1016. if (false === $n = @stream_select($r, $w, $e, 0, $blocking ? ceil(static::TIMEOUT_PRECISION * 1E6) : 0)) {
  1017. // if a system call has been interrupted, forget about it, let's try again
  1018. if ($this->hasSystemCallBeenInterrupted()) {
  1019. continue;
  1020. }
  1021. break;
  1022. }
  1023. // nothing has changed, let's wait until the process is ready
  1024. if (0 === $n) {
  1025. continue;
  1026. }
  1027. if ($w) {
  1028. $written = fwrite($writePipes[0], (binary) substr($this->stdin, $stdinOffset), 8192);
  1029. if (false !== $written) {
  1030. $stdinOffset += $written;
  1031. }
  1032. if ($stdinOffset >= $stdinLen) {
  1033. fclose($writePipes[0]);
  1034. $writePipes = null;
  1035. }
  1036. }
  1037. $this->processReadPipes($r);
  1038. }
  1039. }
  1040. /**
  1041. * Processes read pipes, executes callback on it.
  1042. *
  1043. * @param array $pipes
  1044. */
  1045. private function processReadPipes(array $pipes)
  1046. {
  1047. foreach ($pipes as $pipe) {
  1048. $type = array_search($pipe, $this->pipes);
  1049. $data = fread($pipe, 8192);
  1050. if (strlen($data) > 0) {
  1051. // last exit code is output and caught to work around --enable-sigchild
  1052. if (3 == $type) {
  1053. $this->fallbackExitcode = (int) $data;
  1054. } else {
  1055. call_user_func($this->callback, $type == 1 ? self::OUT : self::ERR, $data);
  1056. }
  1057. }
  1058. if (false === $data || feof($pipe)) {
  1059. fclose($pipe);
  1060. unset($this->pipes[$type]);
  1061. }
  1062. }
  1063. }
  1064. /**
  1065. * Captures the exitcode if mentioned in the process informations.
  1066. */
  1067. private function captureExitCode()
  1068. {
  1069. if (isset($this->processInformation['exitcode']) && -1 != $this->processInformation['exitcode']) {
  1070. $this->exitcode = $this->processInformation['exitcode'];
  1071. }
  1072. }
  1073. /**
  1074. * Closes process resource, closes file handles, sets the exitcode.
  1075. *
  1076. * @return Integer The exitcode
  1077. */
  1078. private function close()
  1079. {
  1080. foreach ($this->pipes as $pipe) {
  1081. fclose($pipe);
  1082. }
  1083. $this->pipes = null;
  1084. $exitcode = -1;
  1085. if (is_resource($this->process)) {
  1086. $exitcode = proc_close($this->process);
  1087. }
  1088. $this->exitcode = $this->exitcode !== null ? $this->exitcode : -1;
  1089. $this->exitcode = -1 != $exitcode ? $exitcode : $this->exitcode;
  1090. if (-1 == $this->exitcode && null !== $this->fallbackExitcode) {
  1091. $this->exitcode = $this->fallbackExitcode;
  1092. } elseif (-1 === $this->exitcode && $this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
  1093. // if process has been signaled, no exitcode but a valid termsig, apply unix convention
  1094. $this->exitcode = 128 + $this->processInformation['termsig'];
  1095. }
  1096. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  1097. foreach ($this->fileHandles as $fileHandle) {
  1098. fclose($fileHandle);
  1099. }
  1100. $this->fileHandles = array();
  1101. }
  1102. return $this->exitcode;
  1103. }
  1104. /**
  1105. * Resets data related to the latest run of the process.
  1106. */
  1107. private function resetProcessData()
  1108. {
  1109. $this->starttime = null;
  1110. $this->callback = null;
  1111. $this->exitcode = null;
  1112. $this->fallbackExitcode = null;
  1113. $this->processInformation = null;
  1114. $this->stdout = null;
  1115. $this->stderr = null;
  1116. $this->pipes = null;
  1117. $this->process = null;
  1118. $this->status = self::STATUS_READY;
  1119. $this->fileHandles = null;
  1120. $this->readBytes = null;
  1121. $this->incrementalOutputOffset = 0;
  1122. $this->incrementalErrorOutputOffset = 0;
  1123. }
  1124. }