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. use Symfony\Component\Process\Pipes\PipesInterface;
  17. use Symfony\Component\Process\Pipes\UnixPipes;
  18. use Symfony\Component\Process\Pipes\WindowsPipes;
  19. /**
  20. * Process is a thin wrapper around proc_* functions to easily
  21. * start independent PHP processes.
  22. *
  23. * @author Fabien Potencier <fabien@symfony.com>
  24. * @author Romain Neutron <imprec@gmail.com>
  25. *
  26. * @api
  27. */
  28. class Process
  29. {
  30. const ERR = 'err';
  31. const OUT = 'out';
  32. const STATUS_READY = 'ready';
  33. const STATUS_STARTED = 'started';
  34. const STATUS_TERMINATED = 'terminated';
  35. const STDIN = 0;
  36. const STDOUT = 1;
  37. const STDERR = 2;
  38. // Timeout Precision in seconds.
  39. const TIMEOUT_PRECISION = 0.2;
  40. private $callback;
  41. private $commandline;
  42. private $cwd;
  43. private $env;
  44. private $input;
  45. private $starttime;
  46. private $lastOutputTime;
  47. private $timeout;
  48. private $idleTimeout;
  49. private $options;
  50. private $exitcode;
  51. private $fallbackExitcode;
  52. private $processInformation;
  53. private $outputDisabled = false;
  54. private $stdout;
  55. private $stderr;
  56. private $enhanceWindowsCompatibility = true;
  57. private $enhanceSigchildCompatibility;
  58. private $process;
  59. private $status = self::STATUS_READY;
  60. private $incrementalOutputOffset = 0;
  61. private $incrementalErrorOutputOffset = 0;
  62. private $tty;
  63. private $pty;
  64. private $useFileHandles = false;
  65. /** @var PipesInterface */
  66. private $processPipes;
  67. private $latestSignal;
  68. private static $sigchild;
  69. /**
  70. * Exit codes translation table.
  71. *
  72. * User-defined errors must use exit codes in the 64-113 range.
  73. *
  74. * @var array
  75. */
  76. public static $exitCodes = array(
  77. 0 => 'OK',
  78. 1 => 'General error',
  79. 2 => 'Misuse of shell builtins',
  80. 126 => 'Invoked command cannot execute',
  81. 127 => 'Command not found',
  82. 128 => 'Invalid exit argument',
  83. // signals
  84. 129 => 'Hangup',
  85. 130 => 'Interrupt',
  86. 131 => 'Quit and dump core',
  87. 132 => 'Illegal instruction',
  88. 133 => 'Trace/breakpoint trap',
  89. 134 => 'Process aborted',
  90. 135 => 'Bus error: "access to undefined portion of memory object"',
  91. 136 => 'Floating point exception: "erroneous arithmetic operation"',
  92. 137 => 'Kill (terminate immediately)',
  93. 138 => 'User-defined 1',
  94. 139 => 'Segmentation violation',
  95. 140 => 'User-defined 2',
  96. 141 => 'Write to pipe with no one reading',
  97. 142 => 'Signal raised by alarm',
  98. 143 => 'Termination (request to terminate)',
  99. // 144 - not defined
  100. 145 => 'Child process terminated, stopped (or continued*)',
  101. 146 => 'Continue if stopped',
  102. 147 => 'Stop executing temporarily',
  103. 148 => 'Terminal stop signal',
  104. 149 => 'Background process attempting to read from tty ("in")',
  105. 150 => 'Background process attempting to write to tty ("out")',
  106. 151 => 'Urgent data available on socket',
  107. 152 => 'CPU time limit exceeded',
  108. 153 => 'File size limit exceeded',
  109. 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
  110. 155 => 'Profiling timer expired',
  111. // 156 - not defined
  112. 157 => 'Pollable event',
  113. // 158 - not defined
  114. 159 => 'Bad syscall',
  115. );
  116. /**
  117. * Constructor.
  118. *
  119. * @param string $commandline The command line to run
  120. * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
  121. * @param array|null $env The environment variables or null to inherit
  122. * @param string|null $input The input
  123. * @param int|float|null $timeout The timeout in seconds or null to disable
  124. * @param array $options An array of options for proc_open
  125. *
  126. * @throws RuntimeException When proc_open is not installed
  127. *
  128. * @api
  129. */
  130. public function __construct($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = array())
  131. {
  132. if (!function_exists('proc_open')) {
  133. throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
  134. }
  135. $this->commandline = $commandline;
  136. $this->cwd = $cwd;
  137. // on Windows, if the cwd changed via chdir(), proc_open defaults to the dir where PHP was started
  138. // on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected
  139. // @see : https://bugs.php.net/bug.php?id=51800
  140. // @see : https://bugs.php.net/bug.php?id=50524
  141. if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || '\\' === DIRECTORY_SEPARATOR)) {
  142. $this->cwd = getcwd();
  143. }
  144. if (null !== $env) {
  145. $this->setEnv($env);
  146. }
  147. $this->input = $input;
  148. $this->setTimeout($timeout);
  149. $this->useFileHandles = '\\' === DIRECTORY_SEPARATOR;
  150. $this->pty = false;
  151. $this->enhanceWindowsCompatibility = true;
  152. $this->enhanceSigchildCompatibility = '\\' !== DIRECTORY_SEPARATOR && $this->isSigchildEnabled();
  153. $this->options = array_replace(array('suppress_errors' => true, 'binary_pipes' => true), $options);
  154. }
  155. public function __destruct()
  156. {
  157. // stop() will check if we have a process running.
  158. $this->stop();
  159. }
  160. public function __clone()
  161. {
  162. $this->resetProcessData();
  163. }
  164. /**
  165. * Runs the process.
  166. *
  167. * The callback receives the type of output (out or err) and
  168. * some bytes from the output in real-time. It allows to have feedback
  169. * from the independent process during execution.
  170. *
  171. * The STDOUT and STDERR are also available after the process is finished
  172. * via the getOutput() and getErrorOutput() methods.
  173. *
  174. * @param callable|null $callback A PHP callback to run whenever there is some
  175. * output available on STDOUT or STDERR
  176. *
  177. * @return int The exit status code
  178. *
  179. * @throws RuntimeException When process can't be launched
  180. * @throws RuntimeException When process stopped after receiving signal
  181. * @throws LogicException In case a callback is provided and output has been disabled
  182. *
  183. * @api
  184. */
  185. public function run($callback = null)
  186. {
  187. $this->start($callback);
  188. return $this->wait();
  189. }
  190. /**
  191. * Runs the process.
  192. *
  193. * This is identical to run() except that an exception is thrown if the process
  194. * exits with a non-zero exit code.
  195. *
  196. * @param callable|null $callback
  197. *
  198. * @return self
  199. *
  200. * @throws RuntimeException if PHP was compiled with --enable-sigchild and the enhanced sigchild compatibility mode is not enabled
  201. * @throws ProcessFailedException if the process didn't terminate successfully
  202. */
  203. public function mustRun($callback = null)
  204. {
  205. if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
  206. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
  207. }
  208. if (0 !== $this->run($callback)) {
  209. throw new ProcessFailedException($this);
  210. }
  211. return $this;
  212. }
  213. /**
  214. * Starts the process and returns after writing the input to STDIN.
  215. *
  216. * This method blocks until all STDIN data is sent to the process then it
  217. * returns while the process runs in the background.
  218. *
  219. * The termination of the process can be awaited with wait().
  220. *
  221. * The callback receives the type of output (out or err) and some bytes from
  222. * the output in real-time while writing the standard input to the process.
  223. * It allows to have feedback from the independent process during execution.
  224. * If there is no callback passed, the wait() method can be called
  225. * with true as a second parameter then the callback will get all data occurred
  226. * in (and since) the start call.
  227. *
  228. * @param callable|null $callback A PHP callback to run whenever there is some
  229. * output available on STDOUT or STDERR
  230. *
  231. * @throws RuntimeException When process can't be launched
  232. * @throws RuntimeException When process is already running
  233. * @throws LogicException In case a callback is provided and output has been disabled
  234. */
  235. public function start($callback = null)
  236. {
  237. if ($this->isRunning()) {
  238. throw new RuntimeException('Process is already running');
  239. }
  240. if ($this->outputDisabled && null !== $callback) {
  241. throw new LogicException('Output has been disabled, enable it to allow the use of a callback.');
  242. }
  243. $this->resetProcessData();
  244. $this->starttime = $this->lastOutputTime = microtime(true);
  245. $this->callback = $this->buildCallback($callback);
  246. $descriptors = $this->getDescriptors();
  247. $commandline = $this->commandline;
  248. if ('\\' === DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) {
  249. $commandline = 'cmd /V:ON /E:ON /C "('.$commandline.')';
  250. foreach ($this->processPipes->getFiles() as $offset => $filename) {
  251. $commandline .= ' '.$offset.'>'.ProcessUtils::escapeArgument($filename);
  252. }
  253. $commandline .= '"';
  254. if (!isset($this->options['bypass_shell'])) {
  255. $this->options['bypass_shell'] = true;
  256. }
  257. }
  258. $this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $this->env, $this->options);
  259. if (!is_resource($this->process)) {
  260. throw new RuntimeException('Unable to launch a new process.');
  261. }
  262. $this->status = self::STATUS_STARTED;
  263. if ($this->tty) {
  264. return;
  265. }
  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->areOpen();
  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. if ($tty && (!file_exists('/dev/tty') || !is_readable('/dev/tty'))) {
  827. throw new RuntimeException('TTY mode requires /dev/tty to be readable.');
  828. }
  829. $this->tty = (bool) $tty;
  830. return $this;
  831. }
  832. /**
  833. * Checks if the TTY mode is enabled.
  834. *
  835. * @return bool true if the TTY mode is enabled, false otherwise
  836. */
  837. public function isTty()
  838. {
  839. return $this->tty;
  840. }
  841. /**
  842. * Sets PTY mode.
  843. *
  844. * @param bool $bool
  845. *
  846. * @return self
  847. */
  848. public function setPty($bool)
  849. {
  850. $this->pty = (bool) $bool;
  851. return $this;
  852. }
  853. /**
  854. * Returns PTY state.
  855. *
  856. * @return bool
  857. */
  858. public function isPty()
  859. {
  860. return $this->pty;
  861. }
  862. /**
  863. * Gets the working directory.
  864. *
  865. * @return string|null The current working directory or null on failure
  866. */
  867. public function getWorkingDirectory()
  868. {
  869. if (null === $this->cwd) {
  870. // getcwd() will return false if any one of the parent directories does not have
  871. // the readable or search mode set, even if the current directory does
  872. return getcwd() ?: null;
  873. }
  874. return $this->cwd;
  875. }
  876. /**
  877. * Sets the current working directory.
  878. *
  879. * @param string $cwd The new working directory
  880. *
  881. * @return self The current Process instance
  882. */
  883. public function setWorkingDirectory($cwd)
  884. {
  885. $this->cwd = $cwd;
  886. return $this;
  887. }
  888. /**
  889. * Gets the environment variables.
  890. *
  891. * @return array The current environment variables
  892. */
  893. public function getEnv()
  894. {
  895. return $this->env;
  896. }
  897. /**
  898. * Sets the environment variables.
  899. *
  900. * An environment variable value should be a string.
  901. * If it is an array, the variable is ignored.
  902. *
  903. * That happens in PHP when 'argv' is registered into
  904. * the $_ENV array for instance.
  905. *
  906. * @param array $env The new environment variables
  907. *
  908. * @return self The current Process instance
  909. */
  910. public function setEnv(array $env)
  911. {
  912. // Process can not handle env values that are arrays
  913. $env = array_filter($env, function ($value) {
  914. return !is_array($value);
  915. });
  916. $this->env = array();
  917. foreach ($env as $key => $value) {
  918. $this->env[(binary) $key] = (binary) $value;
  919. }
  920. return $this;
  921. }
  922. /**
  923. * Gets the contents of STDIN.
  924. *
  925. * @return string|null The current contents
  926. *
  927. * @deprecated Deprecated since version 2.5, to be removed in 3.0.
  928. * This method is deprecated in favor of getInput.
  929. */
  930. public function getStdin()
  931. {
  932. return $this->getInput();
  933. }
  934. /**
  935. * Gets the Process input.
  936. *
  937. * @return null|string The Process input
  938. */
  939. public function getInput()
  940. {
  941. return $this->input;
  942. }
  943. /**
  944. * Sets the contents of STDIN.
  945. *
  946. * @param string|null $stdin The new contents
  947. *
  948. * @return self The current Process instance
  949. *
  950. * @deprecated Deprecated since version 2.5, to be removed in 3.0.
  951. * This method is deprecated in favor of setInput.
  952. *
  953. * @throws LogicException In case the process is running
  954. * @throws InvalidArgumentException In case the argument is invalid
  955. */
  956. public function setStdin($stdin)
  957. {
  958. return $this->setInput($stdin);
  959. }
  960. /**
  961. * Sets the input.
  962. *
  963. * This content will be passed to the underlying process standard input.
  964. *
  965. * @param string|null $input The content
  966. *
  967. * @return self The current Process instance
  968. *
  969. * @throws LogicException In case the process is running
  970. */
  971. public function setInput($input)
  972. {
  973. if ($this->isRunning()) {
  974. throw new LogicException('Input can not be set while the process is running.');
  975. }
  976. $this->input = ProcessUtils::validateInput(sprintf('%s::%s', __CLASS__, __FUNCTION__), $input);
  977. return $this;
  978. }
  979. /**
  980. * Gets the options for proc_open.
  981. *
  982. * @return array The current options
  983. */
  984. public function getOptions()
  985. {
  986. return $this->options;
  987. }
  988. /**
  989. * Sets the options for proc_open.
  990. *
  991. * @param array $options The new options
  992. *
  993. * @return self The current Process instance
  994. */
  995. public function setOptions(array $options)
  996. {
  997. $this->options = $options;
  998. return $this;
  999. }
  1000. /**
  1001. * Gets whether or not Windows compatibility is enabled.
  1002. *
  1003. * This is true by default.
  1004. *
  1005. * @return bool
  1006. */
  1007. public function getEnhanceWindowsCompatibility()
  1008. {
  1009. return $this->enhanceWindowsCompatibility;
  1010. }
  1011. /**
  1012. * Sets whether or not Windows compatibility is enabled.
  1013. *
  1014. * @param bool $enhance
  1015. *
  1016. * @return self The current Process instance
  1017. */
  1018. public function setEnhanceWindowsCompatibility($enhance)
  1019. {
  1020. $this->enhanceWindowsCompatibility = (bool) $enhance;
  1021. return $this;
  1022. }
  1023. /**
  1024. * Returns whether sigchild compatibility mode is activated or not.
  1025. *
  1026. * @return bool
  1027. */
  1028. public function getEnhanceSigchildCompatibility()
  1029. {
  1030. return $this->enhanceSigchildCompatibility;
  1031. }
  1032. /**
  1033. * Activates sigchild compatibility mode.
  1034. *
  1035. * Sigchild compatibility mode is required to get the exit code and
  1036. * determine the success of a process when PHP has been compiled with
  1037. * the --enable-sigchild option
  1038. *
  1039. * @param bool $enhance
  1040. *
  1041. * @return self The current Process instance
  1042. */
  1043. public function setEnhanceSigchildCompatibility($enhance)
  1044. {
  1045. $this->enhanceSigchildCompatibility = (bool) $enhance;
  1046. return $this;
  1047. }
  1048. /**
  1049. * Performs a check between the timeout definition and the time the process started.
  1050. *
  1051. * In case you run a background process (with the start method), you should
  1052. * trigger this method regularly to ensure the process timeout
  1053. *
  1054. * @throws ProcessTimedOutException In case the timeout was reached
  1055. */
  1056. public function checkTimeout()
  1057. {
  1058. if ($this->status !== self::STATUS_STARTED) {
  1059. return;
  1060. }
  1061. if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
  1062. $this->stop(0);
  1063. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL);
  1064. }
  1065. if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
  1066. $this->stop(0);
  1067. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE);
  1068. }
  1069. }
  1070. /**
  1071. * Returns whether PTY is supported on the current operating system.
  1072. *
  1073. * @return bool
  1074. */
  1075. public static function isPtySupported()
  1076. {
  1077. static $result;
  1078. if (null !== $result) {
  1079. return $result;
  1080. }
  1081. if ('\\' === DIRECTORY_SEPARATOR) {
  1082. return $result = false;
  1083. }
  1084. $proc = @proc_open('echo 1', array(array('pty'), array('pty'), array('pty')), $pipes);
  1085. if (is_resource($proc)) {
  1086. proc_close($proc);
  1087. return $result = true;
  1088. }
  1089. return $result = false;
  1090. }
  1091. /**
  1092. * Creates the descriptors needed by the proc_open.
  1093. *
  1094. * @return array
  1095. */
  1096. private function getDescriptors()
  1097. {
  1098. if ('\\' === DIRECTORY_SEPARATOR) {
  1099. $this->processPipes = WindowsPipes::create($this, $this->input);
  1100. } else {
  1101. $this->processPipes = UnixPipes::create($this, $this->input);
  1102. }
  1103. $descriptors = $this->processPipes->getDescriptors($this->outputDisabled);
  1104. if (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  1105. // last exit code is output on the fourth pipe and caught to work around --enable-sigchild
  1106. $descriptors = array_merge($descriptors, array(array('pipe', 'w')));
  1107. $this->commandline = '('.$this->commandline.') 3>/dev/null; code=$?; echo $code >&3; exit $code';
  1108. }
  1109. return $descriptors;
  1110. }
  1111. /**
  1112. * Builds up the callback used by wait().
  1113. *
  1114. * The callbacks adds all occurred output to the specific buffer and calls
  1115. * the user callback (if present) with the received output.
  1116. *
  1117. * @param callable|null $callback The user defined PHP callback
  1118. *
  1119. * @return callable A PHP callable
  1120. */
  1121. protected function buildCallback($callback)
  1122. {
  1123. $that = $this;
  1124. $out = self::OUT;
  1125. $callback = function ($type, $data) use ($that, $callback, $out) {
  1126. if ($out == $type) {
  1127. $that->addOutput($data);
  1128. } else {
  1129. $that->addErrorOutput($data);
  1130. }
  1131. if (null !== $callback) {
  1132. call_user_func($callback, $type, $data);
  1133. }
  1134. };
  1135. return $callback;
  1136. }
  1137. /**
  1138. * Updates the status of the process, reads pipes.
  1139. *
  1140. * @param bool $blocking Whether to use a blocking read call.
  1141. */
  1142. protected function updateStatus($blocking)
  1143. {
  1144. if (self::STATUS_STARTED !== $this->status) {
  1145. return;
  1146. }
  1147. $this->processInformation = proc_get_status($this->process);
  1148. $this->captureExitCode();
  1149. $this->readPipes($blocking, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  1150. if (!$this->processInformation['running']) {
  1151. $this->close();
  1152. }
  1153. }
  1154. /**
  1155. * Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
  1156. *
  1157. * @return bool
  1158. */
  1159. protected function isSigchildEnabled()
  1160. {
  1161. if (null !== self::$sigchild) {
  1162. return self::$sigchild;
  1163. }
  1164. if (!function_exists('phpinfo')) {
  1165. return self::$sigchild = false;
  1166. }
  1167. ob_start();
  1168. phpinfo(INFO_GENERAL);
  1169. return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  1170. }
  1171. /**
  1172. * Validates and returns the filtered timeout.
  1173. *
  1174. * @param int|float|null $timeout
  1175. *
  1176. * @return float|null
  1177. *
  1178. * @throws InvalidArgumentException if the given timeout is a negative number
  1179. */
  1180. private function validateTimeout($timeout)
  1181. {
  1182. $timeout = (float) $timeout;
  1183. if (0.0 === $timeout) {
  1184. $timeout = null;
  1185. } elseif ($timeout < 0) {
  1186. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  1187. }
  1188. return $timeout;
  1189. }
  1190. /**
  1191. * Reads pipes, executes callback.
  1192. *
  1193. * @param bool $blocking Whether to use blocking calls or not.
  1194. * @param bool $close Whether to close file handles or not.
  1195. */
  1196. private function readPipes($blocking, $close)
  1197. {
  1198. $result = $this->processPipes->readAndWrite($blocking, $close);
  1199. $callback = $this->callback;
  1200. foreach ($result as $type => $data) {
  1201. if (3 == $type) {
  1202. $this->fallbackExitcode = (int) $data;
  1203. } else {
  1204. $callback($type === self::STDOUT ? self::OUT : self::ERR, $data);
  1205. }
  1206. }
  1207. }
  1208. /**
  1209. * Captures the exitcode if mentioned in the process information.
  1210. */
  1211. private function captureExitCode()
  1212. {
  1213. if (isset($this->processInformation['exitcode']) && -1 != $this->processInformation['exitcode']) {
  1214. $this->exitcode = $this->processInformation['exitcode'];
  1215. }
  1216. }
  1217. /**
  1218. * Closes process resource, closes file handles, sets the exitcode.
  1219. *
  1220. * @return int The exitcode
  1221. */
  1222. private function close()
  1223. {
  1224. $this->processPipes->close();
  1225. if (is_resource($this->process)) {
  1226. $exitcode = proc_close($this->process);
  1227. } else {
  1228. $exitcode = -1;
  1229. }
  1230. $this->exitcode = -1 !== $exitcode ? $exitcode : (null !== $this->exitcode ? $this->exitcode : -1);
  1231. $this->status = self::STATUS_TERMINATED;
  1232. if (-1 === $this->exitcode && null !== $this->fallbackExitcode) {
  1233. $this->exitcode = $this->fallbackExitcode;
  1234. } elseif (-1 === $this->exitcode && $this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
  1235. // if process has been signaled, no exitcode but a valid termsig, apply Unix convention
  1236. $this->exitcode = 128 + $this->processInformation['termsig'];
  1237. }
  1238. return $this->exitcode;
  1239. }
  1240. /**
  1241. * Resets data related to the latest run of the process.
  1242. */
  1243. private function resetProcessData()
  1244. {
  1245. $this->starttime = null;
  1246. $this->callback = null;
  1247. $this->exitcode = null;
  1248. $this->fallbackExitcode = null;
  1249. $this->processInformation = null;
  1250. $this->stdout = null;
  1251. $this->stderr = null;
  1252. $this->process = null;
  1253. $this->latestSignal = null;
  1254. $this->status = self::STATUS_READY;
  1255. $this->incrementalOutputOffset = 0;
  1256. $this->incrementalErrorOutputOffset = 0;
  1257. }
  1258. /**
  1259. * Sends a POSIX signal to the process.
  1260. *
  1261. * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
  1262. * @param bool $throwException Whether to throw exception in case signal failed
  1263. *
  1264. * @return bool True if the signal was sent successfully, false otherwise
  1265. *
  1266. * @throws LogicException In case the process is not running
  1267. * @throws RuntimeException In case --enable-sigchild is activated
  1268. * @throws RuntimeException In case of failure
  1269. */
  1270. private function doSignal($signal, $throwException)
  1271. {
  1272. if (!$this->isRunning()) {
  1273. if ($throwException) {
  1274. throw new LogicException('Can not send signal on a non running process.');
  1275. }
  1276. return false;
  1277. }
  1278. if ($this->isSigchildEnabled()) {
  1279. if ($throwException) {
  1280. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. The process can not be signaled.');
  1281. }
  1282. return false;
  1283. }
  1284. if (true !== @proc_terminate($this->process, $signal)) {
  1285. if ($throwException) {
  1286. throw new RuntimeException(sprintf('Error while sending signal `%s`.', $signal));
  1287. }
  1288. return false;
  1289. }
  1290. $this->latestSignal = $signal;
  1291. return true;
  1292. }
  1293. /**
  1294. * Ensures the process is running or terminated, throws a LogicException if the process has a not started.
  1295. *
  1296. * @param string $functionName The function name that was called.
  1297. *
  1298. * @throws LogicException If the process has not run.
  1299. */
  1300. private function requireProcessIsStarted($functionName)
  1301. {
  1302. if (!$this->isStarted()) {
  1303. throw new LogicException(sprintf('Process must be started before calling %s.', $functionName));
  1304. }
  1305. }
  1306. /**
  1307. * Ensures the process is terminated, throws a LogicException if the process has a status different than `terminated`.
  1308. *
  1309. * @param string $functionName The function name that was called.
  1310. *
  1311. * @throws LogicException If the process is not yet terminated.
  1312. */
  1313. private function requireProcessIsTerminated($functionName)
  1314. {
  1315. if (!$this->isTerminated()) {
  1316. throw new LogicException(sprintf('Process must be terminated before calling %s.', $functionName));
  1317. }
  1318. }
  1319. }