Process.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519
  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\ProcessFailedException;
  14. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  15. use Symfony\Component\Process\Exception\RuntimeException;
  16. /**
  17. * Process is a thin wrapper around proc_* functions to easily
  18. * start independent PHP processes.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. *
  22. * @api
  23. */
  24. class Process
  25. {
  26. const ERR = 'err';
  27. const OUT = 'out';
  28. const STATUS_READY = 'ready';
  29. const STATUS_STARTED = 'started';
  30. const STATUS_TERMINATED = 'terminated';
  31. const STDIN = 0;
  32. const STDOUT = 1;
  33. const STDERR = 2;
  34. // Timeout Precision in seconds.
  35. const TIMEOUT_PRECISION = 0.2;
  36. private $callback;
  37. private $commandline;
  38. private $cwd;
  39. private $env;
  40. private $input;
  41. private $starttime;
  42. private $lastOutputTime;
  43. private $timeout;
  44. private $idleTimeout;
  45. private $options;
  46. private $exitcode;
  47. private $fallbackExitcode;
  48. private $processInformation;
  49. private $outputDisabled = false;
  50. private $stdout;
  51. private $stderr;
  52. private $enhanceWindowsCompatibility = true;
  53. private $enhanceSigchildCompatibility;
  54. private $process;
  55. private $status = self::STATUS_READY;
  56. private $incrementalOutputOffset = 0;
  57. private $incrementalErrorOutputOffset = 0;
  58. private $tty;
  59. private $pty;
  60. private $useFileHandles = false;
  61. /** @var ProcessPipes */
  62. private $processPipes;
  63. private $latestSignal;
  64. private static $sigchild;
  65. /**
  66. * Exit codes translation table.
  67. *
  68. * User-defined errors must use exit codes in the 64-113 range.
  69. *
  70. * @var array
  71. */
  72. public static $exitCodes = array(
  73. 0 => 'OK',
  74. 1 => 'General error',
  75. 2 => 'Misuse of shell builtins',
  76. 126 => 'Invoked command cannot execute',
  77. 127 => 'Command not found',
  78. 128 => 'Invalid exit argument',
  79. // signals
  80. 129 => 'Hangup',
  81. 130 => 'Interrupt',
  82. 131 => 'Quit and dump core',
  83. 132 => 'Illegal instruction',
  84. 133 => 'Trace/breakpoint trap',
  85. 134 => 'Process aborted',
  86. 135 => 'Bus error: "access to undefined portion of memory object"',
  87. 136 => 'Floating point exception: "erroneous arithmetic operation"',
  88. 137 => 'Kill (terminate immediately)',
  89. 138 => 'User-defined 1',
  90. 139 => 'Segmentation violation',
  91. 140 => 'User-defined 2',
  92. 141 => 'Write to pipe with no one reading',
  93. 142 => 'Signal raised by alarm',
  94. 143 => 'Termination (request to terminate)',
  95. // 144 - not defined
  96. 145 => 'Child process terminated, stopped (or continued*)',
  97. 146 => 'Continue if stopped',
  98. 147 => 'Stop executing temporarily',
  99. 148 => 'Terminal stop signal',
  100. 149 => 'Background process attempting to read from tty ("in")',
  101. 150 => 'Background process attempting to write to tty ("out")',
  102. 151 => 'Urgent data available on socket',
  103. 152 => 'CPU time limit exceeded',
  104. 153 => 'File size limit exceeded',
  105. 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
  106. 155 => 'Profiling timer expired',
  107. // 156 - not defined
  108. 157 => 'Pollable event',
  109. // 158 - not defined
  110. 159 => 'Bad syscall',
  111. );
  112. /**
  113. * Constructor.
  114. *
  115. * @param string $commandline The command line to run
  116. * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
  117. * @param array|null $env The environment variables or null to inherit
  118. * @param string|null $input The input
  119. * @param int|float|null $timeout The timeout in seconds or null to disable
  120. * @param array $options An array of options for proc_open
  121. *
  122. * @throws RuntimeException When proc_open is not installed
  123. *
  124. * @api
  125. */
  126. public function __construct($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = array())
  127. {
  128. if (!function_exists('proc_open')) {
  129. throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
  130. }
  131. $this->commandline = $commandline;
  132. $this->cwd = $cwd;
  133. // on Windows, if the cwd changed via chdir(), proc_open defaults to the dir where PHP was started
  134. // on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected
  135. // @see : https://bugs.php.net/bug.php?id=51800
  136. // @see : https://bugs.php.net/bug.php?id=50524
  137. if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || '\\' === DIRECTORY_SEPARATOR)) {
  138. $this->cwd = getcwd();
  139. }
  140. if (null !== $env) {
  141. $this->setEnv($env);
  142. }
  143. $this->input = $input;
  144. $this->setTimeout($timeout);
  145. $this->useFileHandles = '\\' === DIRECTORY_SEPARATOR;
  146. $this->pty = false;
  147. $this->enhanceWindowsCompatibility = true;
  148. $this->enhanceSigchildCompatibility = '\\' !== DIRECTORY_SEPARATOR && $this->isSigchildEnabled();
  149. $this->options = array_replace(array('suppress_errors' => true, 'binary_pipes' => true), $options);
  150. }
  151. public function __destruct()
  152. {
  153. // stop() will check if we have a process running.
  154. $this->stop();
  155. }
  156. public function __clone()
  157. {
  158. $this->resetProcessData();
  159. }
  160. /**
  161. * Runs the process.
  162. *
  163. * The callback receives the type of output (out or err) and
  164. * some bytes from the output in real-time. It allows to have feedback
  165. * from the independent process during execution.
  166. *
  167. * The STDOUT and STDERR are also available after the process is finished
  168. * via the getOutput() and getErrorOutput() methods.
  169. *
  170. * @param callable|null $callback A PHP callback to run whenever there is some
  171. * output available on STDOUT or STDERR
  172. *
  173. * @return int The exit status code
  174. *
  175. * @throws RuntimeException When process can't be launched
  176. * @throws RuntimeException When process stopped after receiving signal
  177. * @throws LogicException In case a callback is provided and output has been disabled
  178. *
  179. * @api
  180. */
  181. public function run($callback = null)
  182. {
  183. $this->start($callback);
  184. return $this->wait();
  185. }
  186. /**
  187. * Runs the process.
  188. *
  189. * This is identical to run() except that an exception is thrown if the process
  190. * exits with a non-zero exit code.
  191. *
  192. * @param callable|null $callback
  193. *
  194. * @return self
  195. *
  196. * @throws RuntimeException if PHP was compiled with --enable-sigchild and the enhanced sigchild compatibility mode is not enabled
  197. * @throws ProcessFailedException if the process didn't terminate successfully
  198. */
  199. public function mustRun($callback = null)
  200. {
  201. if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
  202. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
  203. }
  204. if (0 !== $this->run($callback)) {
  205. throw new ProcessFailedException($this);
  206. }
  207. return $this;
  208. }
  209. /**
  210. * Starts the process and returns after writing the input to STDIN.
  211. *
  212. * This method blocks until all STDIN data is sent to the process then it
  213. * returns while the process runs in the background.
  214. *
  215. * The termination of the process can be awaited with wait().
  216. *
  217. * The callback receives the type of output (out or err) and some bytes from
  218. * the output in real-time while writing the standard input to the process.
  219. * It allows to have feedback from the independent process during execution.
  220. * If there is no callback passed, the wait() method can be called
  221. * with true as a second parameter then the callback will get all data occurred
  222. * in (and since) the start call.
  223. *
  224. * @param callable|null $callback A PHP callback to run whenever there is some
  225. * output available on STDOUT or STDERR
  226. *
  227. * @return Process The process itself
  228. *
  229. * @throws RuntimeException When process can't be launched
  230. * @throws RuntimeException When process is already running
  231. * @throws LogicException In case a callback is provided and output has been disabled
  232. */
  233. public function start($callback = null)
  234. {
  235. if ($this->isRunning()) {
  236. throw new RuntimeException('Process is already running');
  237. }
  238. if ($this->outputDisabled && null !== $callback) {
  239. throw new LogicException('Output has been disabled, enable it to allow the use of a callback.');
  240. }
  241. $this->resetProcessData();
  242. $this->starttime = $this->lastOutputTime = microtime(true);
  243. $this->callback = $this->buildCallback($callback);
  244. $descriptors = $this->getDescriptors();
  245. $commandline = $this->commandline;
  246. if ('\\' === DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) {
  247. $commandline = 'cmd /V:ON /E:ON /C "('.$commandline.')';
  248. foreach ($this->processPipes->getFiles() as $offset => $filename) {
  249. $commandline .= ' '.$offset.'>'.ProcessUtils::escapeArgument($filename);
  250. }
  251. $commandline .= '"';
  252. if (!isset($this->options['bypass_shell'])) {
  253. $this->options['bypass_shell'] = true;
  254. }
  255. }
  256. $this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $this->env, $this->options);
  257. if (!is_resource($this->process)) {
  258. throw new RuntimeException('Unable to launch a new process.');
  259. }
  260. $this->status = self::STATUS_STARTED;
  261. $this->processPipes->unblock();
  262. if ($this->tty) {
  263. return;
  264. }
  265. $this->processPipes->write(false, $this->input);
  266. $this->updateStatus(false);
  267. $this->checkTimeout();
  268. }
  269. /**
  270. * Restarts the process.
  271. *
  272. * Be warned that the process is cloned before being started.
  273. *
  274. * @param callable|null $callback A PHP callback to run whenever there is some
  275. * output available on STDOUT or STDERR
  276. *
  277. * @return Process The new process
  278. *
  279. * @throws RuntimeException When process can't be launched
  280. * @throws RuntimeException When process is already running
  281. *
  282. * @see start()
  283. */
  284. public function restart($callback = null)
  285. {
  286. if ($this->isRunning()) {
  287. throw new RuntimeException('Process is already running');
  288. }
  289. $process = clone $this;
  290. $process->start($callback);
  291. return $process;
  292. }
  293. /**
  294. * Waits for the process to terminate.
  295. *
  296. * The callback receives the type of output (out or err) and some bytes
  297. * from the output in real-time while writing the standard input to the process.
  298. * It allows to have feedback from the independent process during execution.
  299. *
  300. * @param callable|null $callback A valid PHP callback
  301. *
  302. * @return int The exitcode of the process
  303. *
  304. * @throws RuntimeException When process timed out
  305. * @throws RuntimeException When process stopped after receiving signal
  306. * @throws LogicException When process is not yet started
  307. */
  308. public function wait($callback = null)
  309. {
  310. $this->requireProcessIsStarted(__FUNCTION__);
  311. $this->updateStatus(false);
  312. if (null !== $callback) {
  313. $this->callback = $this->buildCallback($callback);
  314. }
  315. do {
  316. $this->checkTimeout();
  317. $running = '\\' === DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->hasOpenHandles();
  318. $close = '\\' !== DIRECTORY_SEPARATOR || !$running;
  319. $this->readPipes(true, $close);
  320. } while ($running);
  321. while ($this->isRunning()) {
  322. usleep(1000);
  323. }
  324. if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {
  325. throw new RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig']));
  326. }
  327. return $this->exitcode;
  328. }
  329. /**
  330. * Returns the Pid (process identifier), if applicable.
  331. *
  332. * @return int|null The process id if running, null otherwise
  333. *
  334. * @throws RuntimeException In case --enable-sigchild is activated
  335. */
  336. public function getPid()
  337. {
  338. if ($this->isSigchildEnabled()) {
  339. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved.');
  340. }
  341. $this->updateStatus(false);
  342. return $this->isRunning() ? $this->processInformation['pid'] : null;
  343. }
  344. /**
  345. * Sends a POSIX signal to the process.
  346. *
  347. * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
  348. *
  349. * @return Process
  350. *
  351. * @throws LogicException In case the process is not running
  352. * @throws RuntimeException In case --enable-sigchild is activated
  353. * @throws RuntimeException In case of failure
  354. */
  355. public function signal($signal)
  356. {
  357. $this->doSignal($signal, true);
  358. return $this;
  359. }
  360. /**
  361. * Disables fetching output and error output from the underlying process.
  362. *
  363. * @return Process
  364. *
  365. * @throws RuntimeException In case the process is already running
  366. * @throws LogicException if an idle timeout is set
  367. */
  368. public function disableOutput()
  369. {
  370. if ($this->isRunning()) {
  371. throw new RuntimeException('Disabling output while the process is running is not possible.');
  372. }
  373. if (null !== $this->idleTimeout) {
  374. throw new LogicException('Output can not be disabled while an idle timeout is set.');
  375. }
  376. $this->outputDisabled = true;
  377. return $this;
  378. }
  379. /**
  380. * Enables fetching output and error output from the underlying process.
  381. *
  382. * @return Process
  383. *
  384. * @throws RuntimeException In case the process is already running
  385. */
  386. public function enableOutput()
  387. {
  388. if ($this->isRunning()) {
  389. throw new RuntimeException('Enabling output while the process is running is not possible.');
  390. }
  391. $this->outputDisabled = false;
  392. return $this;
  393. }
  394. /**
  395. * Returns true in case the output is disabled, false otherwise.
  396. *
  397. * @return bool
  398. */
  399. public function isOutputDisabled()
  400. {
  401. return $this->outputDisabled;
  402. }
  403. /**
  404. * Returns the current output of the process (STDOUT).
  405. *
  406. * @return string The process output
  407. *
  408. * @throws LogicException in case the output has been disabled
  409. * @throws LogicException In case the process is not started
  410. *
  411. * @api
  412. */
  413. public function getOutput()
  414. {
  415. if ($this->outputDisabled) {
  416. throw new LogicException('Output has been disabled.');
  417. }
  418. $this->requireProcessIsStarted(__FUNCTION__);
  419. $this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  420. return $this->stdout;
  421. }
  422. /**
  423. * Returns the output incrementally.
  424. *
  425. * In comparison with the getOutput method which always return the whole
  426. * output, this one returns the new output since the last call.
  427. *
  428. * @throws LogicException in case the output has been disabled
  429. * @throws LogicException In case the process is not started
  430. *
  431. * @return string The process output since the last call
  432. */
  433. public function getIncrementalOutput()
  434. {
  435. $this->requireProcessIsStarted(__FUNCTION__);
  436. $data = $this->getOutput();
  437. $latest = substr($data, $this->incrementalOutputOffset);
  438. if (false === $latest) {
  439. return '';
  440. }
  441. $this->incrementalOutputOffset = strlen($data);
  442. return $latest;
  443. }
  444. /**
  445. * Clears the process output.
  446. *
  447. * @return Process
  448. */
  449. public function clearOutput()
  450. {
  451. $this->stdout = '';
  452. $this->incrementalOutputOffset = 0;
  453. return $this;
  454. }
  455. /**
  456. * Returns the current error output of the process (STDERR).
  457. *
  458. * @return string The process error output
  459. *
  460. * @throws LogicException in case the output has been disabled
  461. * @throws LogicException In case the process is not started
  462. *
  463. * @api
  464. */
  465. public function getErrorOutput()
  466. {
  467. if ($this->outputDisabled) {
  468. throw new LogicException('Output has been disabled.');
  469. }
  470. $this->requireProcessIsStarted(__FUNCTION__);
  471. $this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  472. return $this->stderr;
  473. }
  474. /**
  475. * Returns the errorOutput incrementally.
  476. *
  477. * In comparison with the getErrorOutput method which always return the
  478. * whole error output, this one returns the new error output since the last
  479. * call.
  480. *
  481. * @throws LogicException in case the output has been disabled
  482. * @throws LogicException In case the process is not started
  483. *
  484. * @return string The process error output since the last call
  485. */
  486. public function getIncrementalErrorOutput()
  487. {
  488. $this->requireProcessIsStarted(__FUNCTION__);
  489. $data = $this->getErrorOutput();
  490. $latest = substr($data, $this->incrementalErrorOutputOffset);
  491. if (false === $latest) {
  492. return '';
  493. }
  494. $this->incrementalErrorOutputOffset = strlen($data);
  495. return $latest;
  496. }
  497. /**
  498. * Clears the process output.
  499. *
  500. * @return Process
  501. */
  502. public function clearErrorOutput()
  503. {
  504. $this->stderr = '';
  505. $this->incrementalErrorOutputOffset = 0;
  506. return $this;
  507. }
  508. /**
  509. * Returns the exit code returned by the process.
  510. *
  511. * @return null|int The exit status code, null if the Process is not terminated
  512. *
  513. * @throws RuntimeException In case --enable-sigchild is activated and the sigchild compatibility mode is disabled
  514. *
  515. * @api
  516. */
  517. public function getExitCode()
  518. {
  519. if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
  520. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
  521. }
  522. $this->updateStatus(false);
  523. return $this->exitcode;
  524. }
  525. /**
  526. * Returns a string representation for the exit code returned by the process.
  527. *
  528. * This method relies on the Unix exit code status standardization
  529. * and might not be relevant for other operating systems.
  530. *
  531. * @return null|string A string representation for the exit status code, null if the Process is not terminated.
  532. *
  533. * @throws RuntimeException In case --enable-sigchild is activated and the sigchild compatibility mode is disabled
  534. *
  535. * @see http://tldp.org/LDP/abs/html/exitcodes.html
  536. * @see http://en.wikipedia.org/wiki/Unix_signal
  537. */
  538. public function getExitCodeText()
  539. {
  540. if (null === $exitcode = $this->getExitCode()) {
  541. return;
  542. }
  543. return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
  544. }
  545. /**
  546. * Checks if the process ended successfully.
  547. *
  548. * @return bool true if the process ended successfully, false otherwise
  549. *
  550. * @api
  551. */
  552. public function isSuccessful()
  553. {
  554. return 0 === $this->getExitCode();
  555. }
  556. /**
  557. * Returns true if the child process has been terminated by an uncaught signal.
  558. *
  559. * It always returns false on Windows.
  560. *
  561. * @return bool
  562. *
  563. * @throws RuntimeException In case --enable-sigchild is activated
  564. * @throws LogicException In case the process is not terminated
  565. *
  566. * @api
  567. */
  568. public function hasBeenSignaled()
  569. {
  570. $this->requireProcessIsTerminated(__FUNCTION__);
  571. if ($this->isSigchildEnabled()) {
  572. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  573. }
  574. $this->updateStatus(false);
  575. return $this->processInformation['signaled'];
  576. }
  577. /**
  578. * Returns the number of the signal that caused the child process to terminate its execution.
  579. *
  580. * It is only meaningful if hasBeenSignaled() returns true.
  581. *
  582. * @return int
  583. *
  584. * @throws RuntimeException In case --enable-sigchild is activated
  585. * @throws LogicException In case the process is not terminated
  586. *
  587. * @api
  588. */
  589. public function getTermSignal()
  590. {
  591. $this->requireProcessIsTerminated(__FUNCTION__);
  592. if ($this->isSigchildEnabled()) {
  593. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  594. }
  595. $this->updateStatus(false);
  596. return $this->processInformation['termsig'];
  597. }
  598. /**
  599. * Returns true if the child process has been stopped by a signal.
  600. *
  601. * It always returns false on Windows.
  602. *
  603. * @return bool
  604. *
  605. * @throws LogicException In case the process is not terminated
  606. *
  607. * @api
  608. */
  609. public function hasBeenStopped()
  610. {
  611. $this->requireProcessIsTerminated(__FUNCTION__);
  612. $this->updateStatus(false);
  613. return $this->processInformation['stopped'];
  614. }
  615. /**
  616. * Returns the number of the signal that caused the child process to stop its execution.
  617. *
  618. * It is only meaningful if hasBeenStopped() returns true.
  619. *
  620. * @return int
  621. *
  622. * @throws LogicException In case the process is not terminated
  623. *
  624. * @api
  625. */
  626. public function getStopSignal()
  627. {
  628. $this->requireProcessIsTerminated(__FUNCTION__);
  629. $this->updateStatus(false);
  630. return $this->processInformation['stopsig'];
  631. }
  632. /**
  633. * Checks if the process is currently running.
  634. *
  635. * @return bool true if the process is currently running, false otherwise
  636. */
  637. public function isRunning()
  638. {
  639. if (self::STATUS_STARTED !== $this->status) {
  640. return false;
  641. }
  642. $this->updateStatus(false);
  643. return $this->processInformation['running'];
  644. }
  645. /**
  646. * Checks if the process has been started with no regard to the current state.
  647. *
  648. * @return bool true if status is ready, false otherwise
  649. */
  650. public function isStarted()
  651. {
  652. return $this->status != self::STATUS_READY;
  653. }
  654. /**
  655. * Checks if the process is terminated.
  656. *
  657. * @return bool true if process is terminated, false otherwise
  658. */
  659. public function isTerminated()
  660. {
  661. $this->updateStatus(false);
  662. return $this->status == self::STATUS_TERMINATED;
  663. }
  664. /**
  665. * Gets the process status.
  666. *
  667. * The status is one of: ready, started, terminated.
  668. *
  669. * @return string The current process status
  670. */
  671. public function getStatus()
  672. {
  673. $this->updateStatus(false);
  674. return $this->status;
  675. }
  676. /**
  677. * Stops the process.
  678. *
  679. * @param int|float $timeout The timeout in seconds
  680. * @param int $signal A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL
  681. *
  682. * @return int The exit-code of the process
  683. *
  684. * @throws RuntimeException if the process got signaled
  685. */
  686. public function stop($timeout = 10, $signal = null)
  687. {
  688. $timeoutMicro = microtime(true) + $timeout;
  689. if ($this->isRunning()) {
  690. if ('\\' === DIRECTORY_SEPARATOR && !$this->isSigchildEnabled()) {
  691. exec(sprintf("taskkill /F /T /PID %d 2>&1", $this->getPid()), $output, $exitCode);
  692. if ($exitCode > 0) {
  693. throw new RuntimeException('Unable to kill the process');
  694. }
  695. }
  696. // given `SIGTERM` may not be defined and that `proc_terminate` uses the constant value and not the constant itself, we use the same here
  697. $this->doSignal(15, false);
  698. do {
  699. usleep(1000);
  700. } while ($this->isRunning() && microtime(true) < $timeoutMicro);
  701. if ($this->isRunning() && !$this->isSigchildEnabled()) {
  702. if (null !== $signal || defined('SIGKILL')) {
  703. // avoid exception here :
  704. // process is supposed to be running, but it might have stop
  705. // just after this line.
  706. // in any case, let's silently discard the error, we can not do anything
  707. $this->doSignal($signal ?: SIGKILL, false);
  708. }
  709. }
  710. }
  711. $this->updateStatus(false);
  712. if ($this->processInformation['running']) {
  713. $this->close();
  714. }
  715. return $this->exitcode;
  716. }
  717. /**
  718. * Adds a line to the STDOUT stream.
  719. *
  720. * @param string $line The line to append
  721. */
  722. public function addOutput($line)
  723. {
  724. $this->lastOutputTime = microtime(true);
  725. $this->stdout .= $line;
  726. }
  727. /**
  728. * Adds a line to the STDERR stream.
  729. *
  730. * @param string $line The line to append
  731. */
  732. public function addErrorOutput($line)
  733. {
  734. $this->lastOutputTime = microtime(true);
  735. $this->stderr .= $line;
  736. }
  737. /**
  738. * Gets the command line to be executed.
  739. *
  740. * @return string The command to execute
  741. */
  742. public function getCommandLine()
  743. {
  744. return $this->commandline;
  745. }
  746. /**
  747. * Sets the command line to be executed.
  748. *
  749. * @param string $commandline The command to execute
  750. *
  751. * @return self The current Process instance
  752. */
  753. public function setCommandLine($commandline)
  754. {
  755. $this->commandline = $commandline;
  756. return $this;
  757. }
  758. /**
  759. * Gets the process timeout (max. runtime).
  760. *
  761. * @return float|null The timeout in seconds or null if it's disabled
  762. */
  763. public function getTimeout()
  764. {
  765. return $this->timeout;
  766. }
  767. /**
  768. * Gets the process idle timeout (max. time since last output).
  769. *
  770. * @return float|null The timeout in seconds or null if it's disabled
  771. */
  772. public function getIdleTimeout()
  773. {
  774. return $this->idleTimeout;
  775. }
  776. /**
  777. * Sets the process timeout (max. runtime).
  778. *
  779. * To disable the timeout, set this value to null.
  780. *
  781. * @param int|float|null $timeout The timeout in seconds
  782. *
  783. * @return self The current Process instance
  784. *
  785. * @throws InvalidArgumentException if the timeout is negative
  786. */
  787. public function setTimeout($timeout)
  788. {
  789. $this->timeout = $this->validateTimeout($timeout);
  790. return $this;
  791. }
  792. /**
  793. * Sets the process idle timeout (max. time since last output).
  794. *
  795. * To disable the timeout, set this value to null.
  796. *
  797. * @param int|float|null $timeout The timeout in seconds
  798. *
  799. * @return self The current Process instance.
  800. *
  801. * @throws LogicException if the output is disabled
  802. * @throws InvalidArgumentException if the timeout is negative
  803. */
  804. public function setIdleTimeout($timeout)
  805. {
  806. if (null !== $timeout && $this->outputDisabled) {
  807. throw new LogicException('Idle timeout can not be set while the output is disabled.');
  808. }
  809. $this->idleTimeout = $this->validateTimeout($timeout);
  810. return $this;
  811. }
  812. /**
  813. * Enables or disables the TTY mode.
  814. *
  815. * @param bool $tty True to enabled and false to disable
  816. *
  817. * @return self The current Process instance
  818. *
  819. * @throws RuntimeException In case the TTY mode is not supported
  820. */
  821. public function setTty($tty)
  822. {
  823. if ('\\' === DIRECTORY_SEPARATOR && $tty) {
  824. throw new RuntimeException('TTY mode is not supported on Windows platform.');
  825. }
  826. $this->tty = (bool) $tty;
  827. return $this;
  828. }
  829. /**
  830. * Checks if the TTY mode is enabled.
  831. *
  832. * @return bool true if the TTY mode is enabled, false otherwise
  833. */
  834. public function isTty()
  835. {
  836. return $this->tty;
  837. }
  838. /**
  839. * Sets PTY mode.
  840. *
  841. * @param bool $bool
  842. *
  843. * @return self
  844. */
  845. public function setPty($bool)
  846. {
  847. $this->pty = (bool) $bool;
  848. return $this;
  849. }
  850. /**
  851. * Returns PTY state.
  852. *
  853. * @return bool
  854. */
  855. public function isPty()
  856. {
  857. return $this->pty;
  858. }
  859. /**
  860. * Gets the working directory.
  861. *
  862. * @return string|null The current working directory or null on failure
  863. */
  864. public function getWorkingDirectory()
  865. {
  866. if (null === $this->cwd) {
  867. // getcwd() will return false if any one of the parent directories does not have
  868. // the readable or search mode set, even if the current directory does
  869. return getcwd() ?: null;
  870. }
  871. return $this->cwd;
  872. }
  873. /**
  874. * Sets the current working directory.
  875. *
  876. * @param string $cwd The new working directory
  877. *
  878. * @return self The current Process instance
  879. */
  880. public function setWorkingDirectory($cwd)
  881. {
  882. $this->cwd = $cwd;
  883. return $this;
  884. }
  885. /**
  886. * Gets the environment variables.
  887. *
  888. * @return array The current environment variables
  889. */
  890. public function getEnv()
  891. {
  892. return $this->env;
  893. }
  894. /**
  895. * Sets the environment variables.
  896. *
  897. * An environment variable value should be a string.
  898. * If it is an array, the variable is ignored.
  899. *
  900. * That happens in PHP when 'argv' is registered into
  901. * the $_ENV array for instance.
  902. *
  903. * @param array $env The new environment variables
  904. *
  905. * @return self The current Process instance
  906. */
  907. public function setEnv(array $env)
  908. {
  909. // Process can not handle env values that are arrays
  910. $env = array_filter($env, function ($value) {
  911. return !is_array($value);
  912. });
  913. $this->env = array();
  914. foreach ($env as $key => $value) {
  915. $this->env[(binary) $key] = (binary) $value;
  916. }
  917. return $this;
  918. }
  919. /**
  920. * Gets the contents of STDIN.
  921. *
  922. * @return string|null The current contents
  923. *
  924. * @deprecated Deprecated since version 2.5, to be removed in 3.0.
  925. * This method is deprecated in favor of getInput.
  926. */
  927. public function getStdin()
  928. {
  929. return $this->getInput();
  930. }
  931. /**
  932. * Gets the Process input.
  933. *
  934. * @return null|string The Process input
  935. */
  936. public function getInput()
  937. {
  938. return $this->input;
  939. }
  940. /**
  941. * Sets the contents of STDIN.
  942. *
  943. * Deprecation: As of Symfony 2.5, this method only accepts scalar values.
  944. *
  945. * @param string|null $stdin The new contents
  946. *
  947. * @return self The current Process instance
  948. *
  949. * @deprecated Deprecated since version 2.5, to be removed in 3.0.
  950. * This method is deprecated in favor of setInput.
  951. *
  952. * @throws LogicException In case the process is running
  953. * @throws InvalidArgumentException In case the argument is invalid
  954. */
  955. public function setStdin($stdin)
  956. {
  957. return $this->setInput($stdin);
  958. }
  959. /**
  960. * Sets the input.
  961. *
  962. * This content will be passed to the underlying process standard input.
  963. *
  964. * @param string|null $input The content
  965. *
  966. * @return self The current Process instance
  967. *
  968. * @throws LogicException In case the process is running
  969. */
  970. public function setInput($input)
  971. {
  972. if ($this->isRunning()) {
  973. throw new LogicException('Input can not be set while the process is running.');
  974. }
  975. $this->input = ProcessUtils::validateInput(sprintf('%s::%s', __CLASS__, __FUNCTION__), $input);
  976. return $this;
  977. }
  978. /**
  979. * Gets the options for proc_open.
  980. *
  981. * @return array The current options
  982. */
  983. public function getOptions()
  984. {
  985. return $this->options;
  986. }
  987. /**
  988. * Sets the options for proc_open.
  989. *
  990. * @param array $options The new options
  991. *
  992. * @return self The current Process instance
  993. */
  994. public function setOptions(array $options)
  995. {
  996. $this->options = $options;
  997. return $this;
  998. }
  999. /**
  1000. * Gets whether or not Windows compatibility is enabled.
  1001. *
  1002. * This is true by default.
  1003. *
  1004. * @return bool
  1005. */
  1006. public function getEnhanceWindowsCompatibility()
  1007. {
  1008. return $this->enhanceWindowsCompatibility;
  1009. }
  1010. /**
  1011. * Sets whether or not Windows compatibility is enabled.
  1012. *
  1013. * @param bool $enhance
  1014. *
  1015. * @return self The current Process instance
  1016. */
  1017. public function setEnhanceWindowsCompatibility($enhance)
  1018. {
  1019. $this->enhanceWindowsCompatibility = (bool) $enhance;
  1020. return $this;
  1021. }
  1022. /**
  1023. * Returns whether sigchild compatibility mode is activated or not.
  1024. *
  1025. * @return bool
  1026. */
  1027. public function getEnhanceSigchildCompatibility()
  1028. {
  1029. return $this->enhanceSigchildCompatibility;
  1030. }
  1031. /**
  1032. * Activates sigchild compatibility mode.
  1033. *
  1034. * Sigchild compatibility mode is required to get the exit code and
  1035. * determine the success of a process when PHP has been compiled with
  1036. * the --enable-sigchild option
  1037. *
  1038. * @param bool $enhance
  1039. *
  1040. * @return self The current Process instance
  1041. */
  1042. public function setEnhanceSigchildCompatibility($enhance)
  1043. {
  1044. $this->enhanceSigchildCompatibility = (bool) $enhance;
  1045. return $this;
  1046. }
  1047. /**
  1048. * Performs a check between the timeout definition and the time the process started.
  1049. *
  1050. * In case you run a background process (with the start method), you should
  1051. * trigger this method regularly to ensure the process timeout
  1052. *
  1053. * @throws ProcessTimedOutException In case the timeout was reached
  1054. */
  1055. public function checkTimeout()
  1056. {
  1057. if ($this->status !== self::STATUS_STARTED) {
  1058. return;
  1059. }
  1060. if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
  1061. $this->stop(0);
  1062. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL);
  1063. }
  1064. if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
  1065. $this->stop(0);
  1066. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE);
  1067. }
  1068. }
  1069. /**
  1070. * Returns whether PTY is supported on the current operating system.
  1071. *
  1072. * @return bool
  1073. */
  1074. public static function isPtySupported()
  1075. {
  1076. static $result;
  1077. if (null !== $result) {
  1078. return $result;
  1079. }
  1080. if ('\\' === DIRECTORY_SEPARATOR) {
  1081. return $result = false;
  1082. }
  1083. $proc = @proc_open('echo 1', array(array('pty'), array('pty'), array('pty')), $pipes);
  1084. if (is_resource($proc)) {
  1085. proc_close($proc);
  1086. return $result = true;
  1087. }
  1088. return $result = false;
  1089. }
  1090. /**
  1091. * Creates the descriptors needed by the proc_open.
  1092. *
  1093. * @return array
  1094. */
  1095. private function getDescriptors()
  1096. {
  1097. $this->processPipes = new ProcessPipes($this->useFileHandles, $this->tty, $this->pty, $this->outputDisabled);
  1098. $descriptors = $this->processPipes->getDescriptors();
  1099. if (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  1100. // last exit code is output on the fourth pipe and caught to work around --enable-sigchild
  1101. $descriptors = array_merge($descriptors, array(array('pipe', 'w')));
  1102. $this->commandline = '('.$this->commandline.') 3>/dev/null; code=$?; echo $code >&3; exit $code';
  1103. }
  1104. return $descriptors;
  1105. }
  1106. /**
  1107. * Builds up the callback used by wait().
  1108. *
  1109. * The callbacks adds all occurred output to the specific buffer and calls
  1110. * the user callback (if present) with the received output.
  1111. *
  1112. * @param callable|null $callback The user defined PHP callback
  1113. *
  1114. * @return callable A PHP callable
  1115. */
  1116. protected function buildCallback($callback)
  1117. {
  1118. $that = $this;
  1119. $out = self::OUT;
  1120. $callback = function ($type, $data) use ($that, $callback, $out) {
  1121. if ($out == $type) {
  1122. $that->addOutput($data);
  1123. } else {
  1124. $that->addErrorOutput($data);
  1125. }
  1126. if (null !== $callback) {
  1127. call_user_func($callback, $type, $data);
  1128. }
  1129. };
  1130. return $callback;
  1131. }
  1132. /**
  1133. * Updates the status of the process, reads pipes.
  1134. *
  1135. * @param bool $blocking Whether to use a blocking read call.
  1136. */
  1137. protected function updateStatus($blocking)
  1138. {
  1139. if (self::STATUS_STARTED !== $this->status) {
  1140. return;
  1141. }
  1142. $this->processInformation = proc_get_status($this->process);
  1143. $this->captureExitCode();
  1144. $this->readPipes($blocking, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  1145. if (!$this->processInformation['running']) {
  1146. $this->close();
  1147. }
  1148. }
  1149. /**
  1150. * Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
  1151. *
  1152. * @return bool
  1153. */
  1154. protected function isSigchildEnabled()
  1155. {
  1156. if (null !== self::$sigchild) {
  1157. return self::$sigchild;
  1158. }
  1159. if (!function_exists('phpinfo')) {
  1160. return self::$sigchild = false;
  1161. }
  1162. ob_start();
  1163. phpinfo(INFO_GENERAL);
  1164. return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  1165. }
  1166. /**
  1167. * Validates and returns the filtered timeout.
  1168. *
  1169. * @param int|float|null $timeout
  1170. *
  1171. * @return float|null
  1172. *
  1173. * @throws InvalidArgumentException if the given timeout is a negative number
  1174. */
  1175. private function validateTimeout($timeout)
  1176. {
  1177. $timeout = (float) $timeout;
  1178. if (0.0 === $timeout) {
  1179. $timeout = null;
  1180. } elseif ($timeout < 0) {
  1181. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  1182. }
  1183. return $timeout;
  1184. }
  1185. /**
  1186. * Reads pipes, executes callback.
  1187. *
  1188. * @param bool $blocking Whether to use blocking calls or not.
  1189. * @param bool $close Whether to close file handles or not.
  1190. */
  1191. private function readPipes($blocking, $close)
  1192. {
  1193. if ($close) {
  1194. $result = $this->processPipes->readAndCloseHandles($blocking);
  1195. } else {
  1196. $result = $this->processPipes->read($blocking);
  1197. }
  1198. $callback = $this->callback;
  1199. foreach ($result as $type => $data) {
  1200. if (3 == $type) {
  1201. $this->fallbackExitcode = (int) $data;
  1202. } else {
  1203. $callback($type === self::STDOUT ? self::OUT : self::ERR, $data);
  1204. }
  1205. }
  1206. }
  1207. /**
  1208. * Captures the exitcode if mentioned in the process information.
  1209. */
  1210. private function captureExitCode()
  1211. {
  1212. if (isset($this->processInformation['exitcode']) && -1 != $this->processInformation['exitcode']) {
  1213. $this->exitcode = $this->processInformation['exitcode'];
  1214. }
  1215. }
  1216. /**
  1217. * Closes process resource, closes file handles, sets the exitcode.
  1218. *
  1219. * @return int The exitcode
  1220. */
  1221. private function close()
  1222. {
  1223. $this->processPipes->close();
  1224. if (is_resource($this->process)) {
  1225. $exitcode = proc_close($this->process);
  1226. } else {
  1227. $exitcode = -1;
  1228. }
  1229. $this->exitcode = -1 !== $exitcode ? $exitcode : (null !== $this->exitcode ? $this->exitcode : -1);
  1230. $this->status = self::STATUS_TERMINATED;
  1231. if (-1 === $this->exitcode && null !== $this->fallbackExitcode) {
  1232. $this->exitcode = $this->fallbackExitcode;
  1233. } elseif (-1 === $this->exitcode && $this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
  1234. // if process has been signaled, no exitcode but a valid termsig, apply Unix convention
  1235. $this->exitcode = 128 + $this->processInformation['termsig'];
  1236. }
  1237. return $this->exitcode;
  1238. }
  1239. /**
  1240. * Resets data related to the latest run of the process.
  1241. */
  1242. private function resetProcessData()
  1243. {
  1244. $this->starttime = null;
  1245. $this->callback = null;
  1246. $this->exitcode = null;
  1247. $this->fallbackExitcode = null;
  1248. $this->processInformation = null;
  1249. $this->stdout = null;
  1250. $this->stderr = null;
  1251. $this->process = null;
  1252. $this->latestSignal = null;
  1253. $this->status = self::STATUS_READY;
  1254. $this->incrementalOutputOffset = 0;
  1255. $this->incrementalErrorOutputOffset = 0;
  1256. }
  1257. /**
  1258. * Sends a POSIX signal to the process.
  1259. *
  1260. * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
  1261. * @param bool $throwException Whether to throw exception in case signal failed
  1262. *
  1263. * @return bool True if the signal was sent successfully, false otherwise
  1264. *
  1265. * @throws LogicException In case the process is not running
  1266. * @throws RuntimeException In case --enable-sigchild is activated
  1267. * @throws RuntimeException In case of failure
  1268. */
  1269. private function doSignal($signal, $throwException)
  1270. {
  1271. if (!$this->isRunning()) {
  1272. if ($throwException) {
  1273. throw new LogicException('Can not send signal on a non running process.');
  1274. }
  1275. return false;
  1276. }
  1277. if ($this->isSigchildEnabled()) {
  1278. if ($throwException) {
  1279. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. The process can not be signaled.');
  1280. }
  1281. return false;
  1282. }
  1283. if (true !== @proc_terminate($this->process, $signal)) {
  1284. if ($throwException) {
  1285. throw new RuntimeException(sprintf('Error while sending signal `%s`.', $signal));
  1286. }
  1287. return false;
  1288. }
  1289. $this->latestSignal = $signal;
  1290. return true;
  1291. }
  1292. /**
  1293. * Ensures the process is running or terminated, throws a LogicException if the process has a not started.
  1294. *
  1295. * @param string $functionName The function name that was called.
  1296. *
  1297. * @throws LogicException If the process has not run.
  1298. */
  1299. private function requireProcessIsStarted($functionName)
  1300. {
  1301. if (!$this->isStarted()) {
  1302. throw new LogicException(sprintf('Process must be started before calling %s.', $functionName));
  1303. }
  1304. }
  1305. /**
  1306. * Ensures the process is terminated, throws a LogicException if the process has a status different than `terminated`.
  1307. *
  1308. * @param string $functionName The function name that was called.
  1309. *
  1310. * @throws LogicException If the process is not yet terminated.
  1311. */
  1312. private function requireProcessIsTerminated($functionName)
  1313. {
  1314. if (!$this->isTerminated()) {
  1315. throw new LogicException(sprintf('Process must be terminated before calling %s.', $functionName));
  1316. }
  1317. }
  1318. }