Process.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  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 easily
  16. * start independent PHP processes.
  17. *
  18. * @author Fabien Potencier <fabien@symfony.com>
  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 $callback;
  33. private $commandline;
  34. private $cwd;
  35. private $env;
  36. private $stdin;
  37. private $starttime;
  38. private $timeout;
  39. private $options;
  40. private $exitcode;
  41. private $fallbackStatus = array();
  42. private $processInformation;
  43. private $stdout;
  44. private $stderr;
  45. private $enhanceWindowsCompatibility = true;
  46. private $enhanceSigchildCompatibility;
  47. private $process;
  48. private $status = self::STATUS_READY;
  49. private $incrementalOutputOffset = 0;
  50. private $incrementalErrorOutputOffset = 0;
  51. private $tty;
  52. private $useFileHandles = false;
  53. /** @var ProcessPipes */
  54. private $processPipes;
  55. private $latestSignal;
  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|null $cwd The working directory or null to use the working dir of the current PHP process
  109. * @param array|null $env The environment variables or null to use the same environment as the current PHP process
  110. * @param string|null $stdin The STDIN content
  111. * @param int|float|null $timeout The timeout in seconds or null to disable
  112. * @param array $options An array of options for proc_open
  113. *
  114. * @throws RuntimeException When proc_open is not installed
  115. */
  116. public function __construct($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array())
  117. {
  118. if (!function_exists('proc_open')) {
  119. throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
  120. }
  121. $this->commandline = $commandline;
  122. $this->cwd = $cwd;
  123. // on Windows, if the cwd changed via chdir(), proc_open defaults to the dir where PHP was started
  124. // on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected
  125. // @see : https://bugs.php.net/bug.php?id=51800
  126. // @see : https://bugs.php.net/bug.php?id=50524
  127. if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || '\\' === DIRECTORY_SEPARATOR)) {
  128. $this->cwd = getcwd();
  129. }
  130. if (null !== $env) {
  131. $this->setEnv($env);
  132. }
  133. $this->stdin = $stdin;
  134. $this->setTimeout($timeout);
  135. $this->useFileHandles = '\\' === DIRECTORY_SEPARATOR;
  136. $this->enhanceSigchildCompatibility = '\\' !== DIRECTORY_SEPARATOR && $this->isSigchildEnabled();
  137. $this->options = array_replace(array('suppress_errors' => true, 'binary_pipes' => true), $options);
  138. }
  139. public function __destruct()
  140. {
  141. $this->stop(0);
  142. }
  143. public function __clone()
  144. {
  145. $this->resetProcessData();
  146. }
  147. /**
  148. * Runs the process.
  149. *
  150. * The callback receives the type of output (out or err) and
  151. * some bytes from the output in real-time. It allows to have feedback
  152. * from the independent process during execution.
  153. *
  154. * The STDOUT and STDERR are also available after the process is finished
  155. * via the getOutput() and getErrorOutput() methods.
  156. *
  157. * @param callback|null $callback A PHP callback to run whenever there is some
  158. * output available on STDOUT or STDERR
  159. *
  160. * @return int The exit status code
  161. *
  162. * @throws RuntimeException When process can't be launched
  163. * @throws RuntimeException When process stopped after receiving signal
  164. */
  165. public function run($callback = null)
  166. {
  167. $this->start($callback);
  168. return $this->wait();
  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. *
  182. * @param callback|null $callback A PHP callback to run whenever there is some
  183. * output available on STDOUT or STDERR
  184. *
  185. * @throws RuntimeException When process can't be launched
  186. * @throws RuntimeException When process is already running
  187. */
  188. public function start($callback = null)
  189. {
  190. if ($this->isRunning()) {
  191. throw new RuntimeException('Process is already running');
  192. }
  193. $this->resetProcessData();
  194. $this->starttime = microtime(true);
  195. $this->callback = $this->buildCallback($callback);
  196. $descriptors = $this->getDescriptors();
  197. $commandline = $this->commandline;
  198. if ('\\' === DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) {
  199. $commandline = 'cmd /V:ON /E:ON /D /C "('.$commandline.')';
  200. foreach ($this->processPipes->getFiles() as $offset => $filename) {
  201. $commandline .= ' '.$offset.'>'.ProcessUtils::escapeArgument($filename);
  202. }
  203. $commandline .= '"';
  204. if (!isset($this->options['bypass_shell'])) {
  205. $this->options['bypass_shell'] = true;
  206. }
  207. } elseif (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  208. // last exit code is output on the fourth pipe and caught to work around --enable-sigchild
  209. $descriptors[3] = array('pipe', 'w');
  210. // See https://unix.stackexchange.com/questions/71205/background-process-pipe-input
  211. $commandline = '{ ('.$this->commandline.') <&3 3<&- 3>/dev/null & } 3<&0;';
  212. $commandline .= 'pid=$!; echo $pid >&3; wait $pid; code=$?; echo $code >&3; exit $code';
  213. // Workaround for the bug, when PTS functionality is enabled.
  214. // @see : https://bugs.php.net/69442
  215. $ptsWorkaround = fopen(__FILE__, 'r');
  216. }
  217. $this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $this->env, $this->options);
  218. if (!is_resource($this->process)) {
  219. throw new RuntimeException('Unable to launch a new process.');
  220. }
  221. $this->status = self::STATUS_STARTED;
  222. if (isset($descriptors[3])) {
  223. $this->fallbackStatus['pid'] = (int) fgets($this->processPipes->pipes[3]);
  224. }
  225. $this->processPipes->unblock();
  226. if ($this->tty) {
  227. return;
  228. }
  229. $this->processPipes->write(false, $this->stdin);
  230. $this->updateStatus(false);
  231. $this->checkTimeout();
  232. }
  233. /**
  234. * Restarts the process.
  235. *
  236. * Be warned that the process is cloned before being started.
  237. *
  238. * @param callable $callback A PHP callback to run whenever there is some
  239. * output available on STDOUT or STDERR
  240. *
  241. * @return Process The new process
  242. *
  243. * @throws RuntimeException When process can't be launched
  244. * @throws RuntimeException When process is already running
  245. *
  246. * @see start()
  247. */
  248. public function restart($callback = null)
  249. {
  250. if ($this->isRunning()) {
  251. throw new RuntimeException('Process is already running');
  252. }
  253. $process = clone $this;
  254. $process->start($callback);
  255. return $process;
  256. }
  257. /**
  258. * Waits for the process to terminate.
  259. *
  260. * The callback receives the type of output (out or err) and some bytes
  261. * from the output in real-time while writing the standard input to the process.
  262. * It allows to have feedback from the independent process during execution.
  263. *
  264. * @param callback|null $callback A valid PHP callback
  265. *
  266. * @return int The exitcode of the process
  267. *
  268. * @throws RuntimeException When process timed out
  269. * @throws RuntimeException When process stopped after receiving signal
  270. * @throws LogicException When process is not yet started
  271. */
  272. public function wait($callback = null)
  273. {
  274. $this->requireProcessIsStarted(__FUNCTION__);
  275. $this->updateStatus(false);
  276. if (null !== $callback) {
  277. $this->callback = $this->buildCallback($callback);
  278. }
  279. do {
  280. $this->checkTimeout();
  281. $running = '\\' === DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->hasOpenHandles();
  282. $close = '\\' !== DIRECTORY_SEPARATOR || !$running;
  283. $this->readPipes(true, $close);
  284. } while ($running);
  285. while ($this->isRunning()) {
  286. usleep(1000);
  287. }
  288. if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {
  289. throw new RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig']));
  290. }
  291. return $this->exitcode;
  292. }
  293. /**
  294. * Returns the Pid (process identifier), if applicable.
  295. *
  296. * @return int|null The process id if running, null otherwise
  297. */
  298. public function getPid()
  299. {
  300. return $this->isRunning() ? $this->processInformation['pid'] : null;
  301. }
  302. /**
  303. * Sends a POSIX signal to the process.
  304. *
  305. * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
  306. *
  307. * @return Process
  308. *
  309. * @throws LogicException In case the process is not running
  310. * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed
  311. * @throws RuntimeException In case of failure
  312. */
  313. public function signal($signal)
  314. {
  315. $this->doSignal($signal, true);
  316. return $this;
  317. }
  318. /**
  319. * Returns the current output of the process (STDOUT).
  320. *
  321. * @return string The process output
  322. *
  323. * @throws LogicException In case the process is not started
  324. */
  325. public function getOutput()
  326. {
  327. $this->requireProcessIsStarted(__FUNCTION__);
  328. $this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  329. if (false === $ret = stream_get_contents($this->stdout, -1, 0)) {
  330. return '';
  331. }
  332. return $ret;
  333. }
  334. /**
  335. * Returns the output incrementally.
  336. *
  337. * In comparison with the getOutput method which always return the whole
  338. * output, this one returns the new output since the last call.
  339. *
  340. * @throws LogicException In case the process is not started
  341. *
  342. * @return string The process output since the last call
  343. */
  344. public function getIncrementalOutput()
  345. {
  346. $this->requireProcessIsStarted(__FUNCTION__);
  347. $latest = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
  348. $this->incrementalOutputOffset = ftell($this->stdout);
  349. if (false === $latest) {
  350. return '';
  351. }
  352. return $latest;
  353. }
  354. /**
  355. * Returns the current error output of the process (STDERR).
  356. *
  357. * @return string The process error output
  358. *
  359. * @throws LogicException In case the process is not started
  360. */
  361. public function getErrorOutput()
  362. {
  363. $this->requireProcessIsStarted(__FUNCTION__);
  364. $this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  365. if (false === $ret = stream_get_contents($this->stderr, -1, 0)) {
  366. return '';
  367. }
  368. return $ret;
  369. }
  370. /**
  371. * Returns the errorOutput incrementally.
  372. *
  373. * In comparison with the getErrorOutput method which always return the
  374. * whole error output, this one returns the new error output since the last
  375. * call.
  376. *
  377. * @throws LogicException In case the process is not started
  378. *
  379. * @return string The process error output since the last call
  380. */
  381. public function getIncrementalErrorOutput()
  382. {
  383. $this->requireProcessIsStarted(__FUNCTION__);
  384. $latest = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
  385. $this->incrementalErrorOutputOffset = ftell($this->stderr);
  386. if (false === $latest) {
  387. return '';
  388. }
  389. return $latest;
  390. }
  391. /**
  392. * Returns the exit code returned by the process.
  393. *
  394. * @return null|int The exit status code, null if the Process is not terminated
  395. *
  396. * @throws RuntimeException In case --enable-sigchild is activated and the sigchild compatibility mode is disabled
  397. */
  398. public function getExitCode()
  399. {
  400. if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  401. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
  402. }
  403. $this->updateStatus(false);
  404. return $this->exitcode;
  405. }
  406. /**
  407. * Returns a string representation for the exit code returned by the process.
  408. *
  409. * This method relies on the Unix exit code status standardization
  410. * and might not be relevant for other operating systems.
  411. *
  412. * @return null|string A string representation for the exit status code, null if the Process is not terminated.
  413. *
  414. * @see http://tldp.org/LDP/abs/html/exitcodes.html
  415. * @see http://en.wikipedia.org/wiki/Unix_signal
  416. */
  417. public function getExitCodeText()
  418. {
  419. if (null === $exitcode = $this->getExitCode()) {
  420. return;
  421. }
  422. return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
  423. }
  424. /**
  425. * Checks if the process ended successfully.
  426. *
  427. * @return bool true if the process ended successfully, false otherwise
  428. */
  429. public function isSuccessful()
  430. {
  431. return 0 === $this->getExitCode();
  432. }
  433. /**
  434. * Returns true if the child process has been terminated by an uncaught signal.
  435. *
  436. * It always returns false on Windows.
  437. *
  438. * @return bool
  439. *
  440. * @throws RuntimeException In case --enable-sigchild is activated
  441. * @throws LogicException In case the process is not terminated
  442. */
  443. public function hasBeenSignaled()
  444. {
  445. $this->requireProcessIsTerminated(__FUNCTION__);
  446. if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  447. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  448. }
  449. return $this->processInformation['signaled'];
  450. }
  451. /**
  452. * Returns the number of the signal that caused the child process to terminate its execution.
  453. *
  454. * It is only meaningful if hasBeenSignaled() returns true.
  455. *
  456. * @return int
  457. *
  458. * @throws RuntimeException In case --enable-sigchild is activated
  459. * @throws LogicException In case the process is not terminated
  460. */
  461. public function getTermSignal()
  462. {
  463. $this->requireProcessIsTerminated(__FUNCTION__);
  464. if ($this->isSigchildEnabled() && (!$this->enhanceSigchildCompatibility || -1 === $this->processInformation['termsig'])) {
  465. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  466. }
  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 bool
  475. *
  476. * @throws LogicException In case the process is not terminated
  477. */
  478. public function hasBeenStopped()
  479. {
  480. $this->requireProcessIsTerminated(__FUNCTION__);
  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 int
  489. *
  490. * @throws LogicException In case the process is not terminated
  491. */
  492. public function getStopSignal()
  493. {
  494. $this->requireProcessIsTerminated(__FUNCTION__);
  495. return $this->processInformation['stopsig'];
  496. }
  497. /**
  498. * Checks if the process is currently running.
  499. *
  500. * @return bool 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 bool 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 bool 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 int|float $timeout The timeout in seconds
  545. * @param int $signal A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL (9)
  546. *
  547. * @return int The exit-code of the process
  548. */
  549. public function stop($timeout = 10, $signal = null)
  550. {
  551. $timeoutMicro = microtime(true) + $timeout;
  552. if ($this->isRunning()) {
  553. // given `SIGTERM` may not be defined and that `proc_terminate` uses the constant value and not the constant itself, we use the same here
  554. $this->doSignal(15, false);
  555. do {
  556. usleep(1000);
  557. } while ($this->isRunning() && microtime(true) < $timeoutMicro);
  558. if ($this->isRunning()) {
  559. // Avoid exception here: process is supposed to be running, but it might have stopped just
  560. // after this line. In any case, let's silently discard the error, we cannot do anything.
  561. $this->doSignal($signal ?: 9, false);
  562. }
  563. }
  564. if ($this->isRunning()) {
  565. if (isset($this->fallbackStatus['pid'])) {
  566. unset($this->fallbackStatus['pid']);
  567. return $this->stop(0, $signal);
  568. }
  569. $this->close();
  570. }
  571. return $this->exitcode;
  572. }
  573. /**
  574. * Adds a line to the STDOUT stream.
  575. *
  576. * @internal
  577. *
  578. * @param string $line The line to append
  579. */
  580. public function addOutput($line)
  581. {
  582. fseek($this->stdout, 0, SEEK_END);
  583. fwrite($this->stdout, $line);
  584. fseek($this->stdout, $this->incrementalOutputOffset);
  585. }
  586. /**
  587. * Adds a line to the STDERR stream.
  588. *
  589. * @internal
  590. *
  591. * @param string $line The line to append
  592. */
  593. public function addErrorOutput($line)
  594. {
  595. fseek($this->stderr, 0, SEEK_END);
  596. fwrite($this->stderr, $line);
  597. fseek($this->stderr, $this->incrementalErrorOutputOffset);
  598. }
  599. /**
  600. * Gets the command line to be executed.
  601. *
  602. * @return string The command to execute
  603. */
  604. public function getCommandLine()
  605. {
  606. return $this->commandline;
  607. }
  608. /**
  609. * Sets the command line to be executed.
  610. *
  611. * @param string $commandline The command to execute
  612. *
  613. * @return self The current Process instance
  614. */
  615. public function setCommandLine($commandline)
  616. {
  617. $this->commandline = $commandline;
  618. return $this;
  619. }
  620. /**
  621. * Gets the process timeout.
  622. *
  623. * @return float|null The timeout in seconds or null if it's disabled
  624. */
  625. public function getTimeout()
  626. {
  627. return $this->timeout;
  628. }
  629. /**
  630. * Sets the process timeout.
  631. *
  632. * To disable the timeout, set this value to null.
  633. *
  634. * @param int|float|null $timeout The timeout in seconds
  635. *
  636. * @return self The current Process instance
  637. *
  638. * @throws InvalidArgumentException if the timeout is negative
  639. */
  640. public function setTimeout($timeout)
  641. {
  642. $timeout = (float) $timeout;
  643. if (0.0 === $timeout) {
  644. $timeout = null;
  645. } elseif ($timeout < 0) {
  646. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  647. }
  648. $this->timeout = $timeout;
  649. return $this;
  650. }
  651. /**
  652. * Enables or disables the TTY mode.
  653. *
  654. * @param bool $tty True to enabled and false to disable
  655. *
  656. * @return self The current Process instance
  657. *
  658. * @throws RuntimeException In case the TTY mode is not supported
  659. */
  660. public function setTty($tty)
  661. {
  662. if ('\\' === DIRECTORY_SEPARATOR && $tty) {
  663. throw new RuntimeException('TTY mode is not supported on Windows platform.');
  664. }
  665. if ($tty && (!file_exists('/dev/tty') || !is_readable('/dev/tty'))) {
  666. throw new RuntimeException('TTY mode requires /dev/tty to be readable.');
  667. }
  668. $this->tty = (bool) $tty;
  669. return $this;
  670. }
  671. /**
  672. * Checks if the TTY mode is enabled.
  673. *
  674. * @return bool true if the TTY mode is enabled, false otherwise
  675. */
  676. public function isTty()
  677. {
  678. return $this->tty;
  679. }
  680. /**
  681. * Gets the working directory.
  682. *
  683. * @return string|null The current working directory or null on failure
  684. */
  685. public function getWorkingDirectory()
  686. {
  687. if (null === $this->cwd) {
  688. // getcwd() will return false if any one of the parent directories does not have
  689. // the readable or search mode set, even if the current directory does
  690. return getcwd() ?: null;
  691. }
  692. return $this->cwd;
  693. }
  694. /**
  695. * Sets the current working directory.
  696. *
  697. * @param string $cwd The new working directory
  698. *
  699. * @return self The current Process instance
  700. */
  701. public function setWorkingDirectory($cwd)
  702. {
  703. $this->cwd = $cwd;
  704. return $this;
  705. }
  706. /**
  707. * Gets the environment variables.
  708. *
  709. * @return array The current environment variables
  710. */
  711. public function getEnv()
  712. {
  713. return $this->env;
  714. }
  715. /**
  716. * Sets the environment variables.
  717. *
  718. * An environment variable value should be a string.
  719. * If it is an array, the variable is ignored.
  720. *
  721. * That happens in PHP when 'argv' is registered into
  722. * the $_ENV array for instance.
  723. *
  724. * @param array $env The new environment variables
  725. *
  726. * @return self The current Process instance
  727. */
  728. public function setEnv(array $env)
  729. {
  730. // Process can not handle env values that are arrays
  731. $env = array_filter($env, function ($value) {
  732. return !is_array($value);
  733. });
  734. $this->env = array();
  735. foreach ($env as $key => $value) {
  736. $this->env[$key] = (string) $value;
  737. }
  738. return $this;
  739. }
  740. /**
  741. * Gets the contents of STDIN.
  742. *
  743. * @return string|null The current contents
  744. */
  745. public function getStdin()
  746. {
  747. return $this->stdin;
  748. }
  749. /**
  750. * Sets the contents of STDIN.
  751. *
  752. * @param string|null $stdin The new contents
  753. *
  754. * @return self The current Process instance
  755. *
  756. * @throws LogicException In case the process is running
  757. * @throws InvalidArgumentException In case the argument is invalid
  758. */
  759. public function setStdin($stdin)
  760. {
  761. if ($this->isRunning()) {
  762. throw new LogicException('STDIN can not be set while the process is running.');
  763. }
  764. $this->stdin = ProcessUtils::validateInput(__METHOD__, $stdin);
  765. return $this;
  766. }
  767. /**
  768. * Gets the options for proc_open.
  769. *
  770. * @return array The current options
  771. */
  772. public function getOptions()
  773. {
  774. return $this->options;
  775. }
  776. /**
  777. * Sets the options for proc_open.
  778. *
  779. * @param array $options The new options
  780. *
  781. * @return self The current Process instance
  782. */
  783. public function setOptions(array $options)
  784. {
  785. $this->options = $options;
  786. return $this;
  787. }
  788. /**
  789. * Gets whether or not Windows compatibility is enabled.
  790. *
  791. * This is true by default.
  792. *
  793. * @return bool
  794. */
  795. public function getEnhanceWindowsCompatibility()
  796. {
  797. return $this->enhanceWindowsCompatibility;
  798. }
  799. /**
  800. * Sets whether or not Windows compatibility is enabled.
  801. *
  802. * @param bool $enhance
  803. *
  804. * @return self The current Process instance
  805. */
  806. public function setEnhanceWindowsCompatibility($enhance)
  807. {
  808. $this->enhanceWindowsCompatibility = (bool) $enhance;
  809. return $this;
  810. }
  811. /**
  812. * Returns whether sigchild compatibility mode is activated or not.
  813. *
  814. * @return bool
  815. */
  816. public function getEnhanceSigchildCompatibility()
  817. {
  818. return $this->enhanceSigchildCompatibility;
  819. }
  820. /**
  821. * Activates sigchild compatibility mode.
  822. *
  823. * Sigchild compatibility mode is required to get the exit code and
  824. * determine the success of a process when PHP has been compiled with
  825. * the --enable-sigchild option
  826. *
  827. * @param bool $enhance
  828. *
  829. * @return self The current Process instance
  830. */
  831. public function setEnhanceSigchildCompatibility($enhance)
  832. {
  833. $this->enhanceSigchildCompatibility = (bool) $enhance;
  834. return $this;
  835. }
  836. /**
  837. * Performs a check between the timeout definition and the time the process started.
  838. *
  839. * In case you run a background process (with the start method), you should
  840. * trigger this method regularly to ensure the process timeout
  841. *
  842. * @throws RuntimeException In case the timeout was reached
  843. */
  844. public function checkTimeout()
  845. {
  846. if ($this->status !== self::STATUS_STARTED) {
  847. return;
  848. }
  849. if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
  850. $this->stop(0);
  851. throw new RuntimeException('The process timed-out.');
  852. }
  853. }
  854. /**
  855. * Creates the descriptors needed by the proc_open.
  856. *
  857. * @return array
  858. */
  859. private function getDescriptors()
  860. {
  861. $this->processPipes = new ProcessPipes($this->useFileHandles, $this->tty);
  862. return $this->processPipes->getDescriptors();
  863. }
  864. /**
  865. * Builds up the callback used by wait().
  866. *
  867. * The callbacks adds all occurred output to the specific buffer and calls
  868. * the user callback (if present) with the received output.
  869. *
  870. * @param callback|null $callback The user defined PHP callback
  871. *
  872. * @return \Closure A PHP closure
  873. */
  874. protected function buildCallback($callback)
  875. {
  876. $that = $this;
  877. $out = self::OUT;
  878. $callback = function ($type, $data) use ($that, $callback, $out) {
  879. if ($out == $type) {
  880. $that->addOutput($data);
  881. } else {
  882. $that->addErrorOutput($data);
  883. }
  884. if (null !== $callback) {
  885. call_user_func($callback, $type, $data);
  886. }
  887. };
  888. return $callback;
  889. }
  890. /**
  891. * Updates the status of the process, reads pipes.
  892. *
  893. * @param bool $blocking Whether to use a blocking read call.
  894. */
  895. protected function updateStatus($blocking)
  896. {
  897. if (self::STATUS_STARTED !== $this->status) {
  898. return;
  899. }
  900. $this->processInformation = proc_get_status($this->process);
  901. $this->readPipes($blocking, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  902. if ($this->fallbackStatus && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  903. $this->processInformation = $this->fallbackStatus + $this->processInformation;
  904. }
  905. if (!$this->processInformation['running']) {
  906. $this->close();
  907. }
  908. }
  909. /**
  910. * Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
  911. *
  912. * @return bool
  913. */
  914. protected function isSigchildEnabled()
  915. {
  916. if (null !== self::$sigchild) {
  917. return self::$sigchild;
  918. }
  919. if (!function_exists('phpinfo') || defined('HHVM_VERSION')) {
  920. return self::$sigchild = false;
  921. }
  922. ob_start();
  923. phpinfo(INFO_GENERAL);
  924. return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  925. }
  926. /**
  927. * Reads pipes, executes callback.
  928. *
  929. * @param bool $blocking Whether to use blocking calls or not.
  930. * @param bool $close Whether to close file handles or not.
  931. */
  932. private function readPipes($blocking, $close)
  933. {
  934. if ($close) {
  935. $result = $this->processPipes->readAndCloseHandles($blocking);
  936. } else {
  937. $result = $this->processPipes->read($blocking);
  938. }
  939. $callback = $this->callback;
  940. foreach ($result as $type => $data) {
  941. if (3 !== $type) {
  942. $callback($type === self::STDOUT ? self::OUT : self::ERR, $data);
  943. } elseif (!isset($this->fallbackStatus['signaled'])) {
  944. $this->fallbackStatus['exitcode'] = (int) $data;
  945. }
  946. }
  947. }
  948. /**
  949. * Closes process resource, closes file handles, sets the exitcode.
  950. *
  951. * @return int The exitcode
  952. */
  953. private function close()
  954. {
  955. $this->processPipes->close();
  956. if (is_resource($this->process)) {
  957. proc_close($this->process);
  958. }
  959. $this->exitcode = $this->processInformation['exitcode'];
  960. $this->status = self::STATUS_TERMINATED;
  961. if (-1 === $this->exitcode) {
  962. if ($this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
  963. // if process has been signaled, no exitcode but a valid termsig, apply Unix convention
  964. $this->exitcode = 128 + $this->processInformation['termsig'];
  965. } elseif ($this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  966. $this->processInformation['signaled'] = true;
  967. $this->processInformation['termsig'] = -1;
  968. }
  969. }
  970. // Free memory from self-reference callback created by buildCallback
  971. // Doing so in other contexts like __destruct or by garbage collector is ineffective
  972. // Now pipes are closed, so the callback is no longer necessary
  973. $this->callback = null;
  974. return $this->exitcode;
  975. }
  976. /**
  977. * Resets data related to the latest run of the process.
  978. */
  979. private function resetProcessData()
  980. {
  981. $this->starttime = null;
  982. $this->callback = null;
  983. $this->exitcode = null;
  984. $this->fallbackStatus = array();
  985. $this->processInformation = null;
  986. $this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'wb+');
  987. $this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'wb+');
  988. $this->process = null;
  989. $this->latestSignal = null;
  990. $this->status = self::STATUS_READY;
  991. $this->incrementalOutputOffset = 0;
  992. $this->incrementalErrorOutputOffset = 0;
  993. }
  994. /**
  995. * Sends a POSIX signal to the process.
  996. *
  997. * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
  998. * @param bool $throwException Whether to throw exception in case signal failed
  999. *
  1000. * @return bool True if the signal was sent successfully, false otherwise
  1001. *
  1002. * @throws LogicException In case the process is not running
  1003. * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed
  1004. * @throws RuntimeException In case of failure
  1005. */
  1006. private function doSignal($signal, $throwException)
  1007. {
  1008. if (null === $pid = $this->getPid()) {
  1009. if ($throwException) {
  1010. throw new LogicException('Can not send signal on a non running process.');
  1011. }
  1012. return false;
  1013. }
  1014. if ('\\' === DIRECTORY_SEPARATOR) {
  1015. exec(sprintf('taskkill /F /T /PID %d 2>&1', $pid), $output, $exitCode);
  1016. if ($exitCode && $this->isRunning()) {
  1017. if ($throwException) {
  1018. throw new RuntimeException(sprintf('Unable to kill the process (%s).', implode(' ', $output)));
  1019. }
  1020. return false;
  1021. }
  1022. } else {
  1023. if (!$this->enhanceSigchildCompatibility || !$this->isSigchildEnabled()) {
  1024. $ok = @proc_terminate($this->process, $signal);
  1025. } elseif (function_exists('posix_kill')) {
  1026. $ok = @posix_kill($pid, $signal);
  1027. } elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), array(2 => array('pipe', 'w')), $pipes)) {
  1028. $ok = false === fgets($pipes[2]);
  1029. }
  1030. if (!$ok) {
  1031. if ($throwException) {
  1032. throw new RuntimeException(sprintf('Error while sending signal `%s`.', $signal));
  1033. }
  1034. return false;
  1035. }
  1036. }
  1037. $this->latestSignal = (int) $signal;
  1038. $this->fallbackStatus['signaled'] = true;
  1039. $this->fallbackStatus['exitcode'] = -1;
  1040. $this->fallbackStatus['termsig'] = $this->latestSignal;
  1041. return true;
  1042. }
  1043. /**
  1044. * Ensures the process is running or terminated, throws a LogicException if the process has a not started.
  1045. *
  1046. * @param string $functionName The function name that was called.
  1047. *
  1048. * @throws LogicException If the process has not run.
  1049. */
  1050. private function requireProcessIsStarted($functionName)
  1051. {
  1052. if (!$this->isStarted()) {
  1053. throw new LogicException(sprintf('Process must be started before calling %s.', $functionName));
  1054. }
  1055. }
  1056. /**
  1057. * Ensures the process is terminated, throws a LogicException if the process has a status different than `terminated`.
  1058. *
  1059. * @param string $functionName The function name that was called.
  1060. *
  1061. * @throws LogicException If the process is not yet terminated.
  1062. */
  1063. private function requireProcessIsTerminated($functionName)
  1064. {
  1065. if (!$this->isTerminated()) {
  1066. throw new LogicException(sprintf('Process must be terminated before calling %s.', $functionName));
  1067. }
  1068. }
  1069. }