No Description

Process.php 44KB

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. * @return Process The process itself
  232. *
  233. * @throws RuntimeException When process can't be launched
  234. * @throws RuntimeException When process is already running
  235. * @throws LogicException In case a callback is provided and output has been disabled
  236. */
  237. public function start($callback = null)
  238. {
  239. if ($this->isRunning()) {
  240. throw new RuntimeException('Process is already running');
  241. }
  242. if ($this->outputDisabled && null !== $callback) {
  243. throw new LogicException('Output has been disabled, enable it to allow the use of a callback.');
  244. }
  245. $this->resetProcessData();
  246. $this->starttime = $this->lastOutputTime = microtime(true);
  247. $this->callback = $this->buildCallback($callback);
  248. $descriptors = $this->getDescriptors();
  249. $commandline = $this->commandline;
  250. if ('\\' === DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) {
  251. $commandline = 'cmd /V:ON /E:ON /C "('.$commandline.')';
  252. foreach ($this->processPipes->getFiles() as $offset => $filename) {
  253. $commandline .= ' '.$offset.'>'.ProcessUtils::escapeArgument($filename);
  254. }
  255. $commandline .= '"';
  256. if (!isset($this->options['bypass_shell'])) {
  257. $this->options['bypass_shell'] = true;
  258. }
  259. }
  260. $this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $this->env, $this->options);
  261. if (!is_resource($this->process)) {
  262. throw new RuntimeException('Unable to launch a new process.');
  263. }
  264. $this->status = self::STATUS_STARTED;
  265. if ($this->tty) {
  266. return;
  267. }
  268. $this->updateStatus(false);
  269. $this->checkTimeout();
  270. }
  271. /**
  272. * Restarts the process.
  273. *
  274. * Be warned that the process is cloned before being started.
  275. *
  276. * @param callable|null $callback A PHP callback to run whenever there is some
  277. * output available on STDOUT or STDERR
  278. *
  279. * @return Process The new process
  280. *
  281. * @throws RuntimeException When process can't be launched
  282. * @throws RuntimeException When process is already running
  283. *
  284. * @see start()
  285. */
  286. public function restart($callback = null)
  287. {
  288. if ($this->isRunning()) {
  289. throw new RuntimeException('Process is already running');
  290. }
  291. $process = clone $this;
  292. $process->start($callback);
  293. return $process;
  294. }
  295. /**
  296. * Waits for the process to terminate.
  297. *
  298. * The callback receives the type of output (out or err) and some bytes
  299. * from the output in real-time while writing the standard input to the process.
  300. * It allows to have feedback from the independent process during execution.
  301. *
  302. * @param callable|null $callback A valid PHP callback
  303. *
  304. * @return int The exitcode of the process
  305. *
  306. * @throws RuntimeException When process timed out
  307. * @throws RuntimeException When process stopped after receiving signal
  308. * @throws LogicException When process is not yet started
  309. */
  310. public function wait($callback = null)
  311. {
  312. $this->requireProcessIsStarted(__FUNCTION__);
  313. $this->updateStatus(false);
  314. if (null !== $callback) {
  315. $this->callback = $this->buildCallback($callback);
  316. }
  317. do {
  318. $this->checkTimeout();
  319. $running = '\\' === DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
  320. $close = '\\' !== DIRECTORY_SEPARATOR || !$running;
  321. $this->readPipes(true, $close);
  322. } while ($running);
  323. while ($this->isRunning()) {
  324. usleep(1000);
  325. }
  326. if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {
  327. throw new RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig']));
  328. }
  329. return $this->exitcode;
  330. }
  331. /**
  332. * Returns the Pid (process identifier), if applicable.
  333. *
  334. * @return int|null The process id if running, null otherwise
  335. *
  336. * @throws RuntimeException In case --enable-sigchild is activated
  337. */
  338. public function getPid()
  339. {
  340. if ($this->isSigchildEnabled()) {
  341. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved.');
  342. }
  343. $this->updateStatus(false);
  344. return $this->isRunning() ? $this->processInformation['pid'] : null;
  345. }
  346. /**
  347. * Sends a POSIX signal to the process.
  348. *
  349. * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
  350. *
  351. * @return Process
  352. *
  353. * @throws LogicException In case the process is not running
  354. * @throws RuntimeException In case --enable-sigchild is activated
  355. * @throws RuntimeException In case of failure
  356. */
  357. public function signal($signal)
  358. {
  359. $this->doSignal($signal, true);
  360. return $this;
  361. }
  362. /**
  363. * Disables fetching output and error output from the underlying process.
  364. *
  365. * @return Process
  366. *
  367. * @throws RuntimeException In case the process is already running
  368. * @throws LogicException if an idle timeout is set
  369. */
  370. public function disableOutput()
  371. {
  372. if ($this->isRunning()) {
  373. throw new RuntimeException('Disabling output while the process is running is not possible.');
  374. }
  375. if (null !== $this->idleTimeout) {
  376. throw new LogicException('Output can not be disabled while an idle timeout is set.');
  377. }
  378. $this->outputDisabled = true;
  379. return $this;
  380. }
  381. /**
  382. * Enables fetching output and error output from the underlying process.
  383. *
  384. * @return Process
  385. *
  386. * @throws RuntimeException In case the process is already running
  387. */
  388. public function enableOutput()
  389. {
  390. if ($this->isRunning()) {
  391. throw new RuntimeException('Enabling output while the process is running is not possible.');
  392. }
  393. $this->outputDisabled = false;
  394. return $this;
  395. }
  396. /**
  397. * Returns true in case the output is disabled, false otherwise.
  398. *
  399. * @return bool
  400. */
  401. public function isOutputDisabled()
  402. {
  403. return $this->outputDisabled;
  404. }
  405. /**
  406. * Returns the current output of the process (STDOUT).
  407. *
  408. * @return string The process output
  409. *
  410. * @throws LogicException in case the output has been disabled
  411. * @throws LogicException In case the process is not started
  412. *
  413. * @api
  414. */
  415. public function getOutput()
  416. {
  417. if ($this->outputDisabled) {
  418. throw new LogicException('Output has been disabled.');
  419. }
  420. $this->requireProcessIsStarted(__FUNCTION__);
  421. $this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  422. return $this->stdout;
  423. }
  424. /**
  425. * Returns the output incrementally.
  426. *
  427. * In comparison with the getOutput method which always return the whole
  428. * output, this one returns the new output since the last call.
  429. *
  430. * @throws LogicException in case the output has been disabled
  431. * @throws LogicException In case the process is not started
  432. *
  433. * @return string The process output since the last call
  434. */
  435. public function getIncrementalOutput()
  436. {
  437. $this->requireProcessIsStarted(__FUNCTION__);
  438. $data = $this->getOutput();
  439. $latest = substr($data, $this->incrementalOutputOffset);
  440. if (false === $latest) {
  441. return '';
  442. }
  443. $this->incrementalOutputOffset = strlen($data);
  444. return $latest;
  445. }
  446. /**
  447. * Clears the process output.
  448. *
  449. * @return Process
  450. */
  451. public function clearOutput()
  452. {
  453. $this->stdout = '';
  454. $this->incrementalOutputOffset = 0;
  455. return $this;
  456. }
  457. /**
  458. * Returns the current error output of the process (STDERR).
  459. *
  460. * @return string The process error output
  461. *
  462. * @throws LogicException in case the output has been disabled
  463. * @throws LogicException In case the process is not started
  464. *
  465. * @api
  466. */
  467. public function getErrorOutput()
  468. {
  469. if ($this->outputDisabled) {
  470. throw new LogicException('Output has been disabled.');
  471. }
  472. $this->requireProcessIsStarted(__FUNCTION__);
  473. $this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  474. return $this->stderr;
  475. }
  476. /**
  477. * Returns the errorOutput incrementally.
  478. *
  479. * In comparison with the getErrorOutput method which always return the
  480. * whole error output, this one returns the new error output since the last
  481. * call.
  482. *
  483. * @throws LogicException in case the output has been disabled
  484. * @throws LogicException In case the process is not started
  485. *
  486. * @return string The process error output since the last call
  487. */
  488. public function getIncrementalErrorOutput()
  489. {
  490. $this->requireProcessIsStarted(__FUNCTION__);
  491. $data = $this->getErrorOutput();
  492. $latest = substr($data, $this->incrementalErrorOutputOffset);
  493. if (false === $latest) {
  494. return '';
  495. }
  496. $this->incrementalErrorOutputOffset = strlen($data);
  497. return $latest;
  498. }
  499. /**
  500. * Clears the process output.
  501. *
  502. * @return Process
  503. */
  504. public function clearErrorOutput()
  505. {
  506. $this->stderr = '';
  507. $this->incrementalErrorOutputOffset = 0;
  508. return $this;
  509. }
  510. /**
  511. * Returns the exit code returned by the process.
  512. *
  513. * @return null|int The exit status code, null if the Process is not terminated
  514. *
  515. * @throws RuntimeException In case --enable-sigchild is activated and the sigchild compatibility mode is disabled
  516. *
  517. * @api
  518. */
  519. public function getExitCode()
  520. {
  521. if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
  522. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
  523. }
  524. $this->updateStatus(false);
  525. return $this->exitcode;
  526. }
  527. /**
  528. * Returns a string representation for the exit code returned by the process.
  529. *
  530. * This method relies on the Unix exit code status standardization
  531. * and might not be relevant for other operating systems.
  532. *
  533. * @return null|string A string representation for the exit status code, null if the Process is not terminated.
  534. *
  535. * @throws RuntimeException In case --enable-sigchild is activated and the sigchild compatibility mode is disabled
  536. *
  537. * @see http://tldp.org/LDP/abs/html/exitcodes.html
  538. * @see http://en.wikipedia.org/wiki/Unix_signal
  539. */
  540. public function getExitCodeText()
  541. {
  542. if (null === $exitcode = $this->getExitCode()) {
  543. return;
  544. }
  545. return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
  546. }
  547. /**
  548. * Checks if the process ended successfully.
  549. *
  550. * @return bool true if the process ended successfully, false otherwise
  551. *
  552. * @api
  553. */
  554. public function isSuccessful()
  555. {
  556. return 0 === $this->getExitCode();
  557. }
  558. /**
  559. * Returns true if the child process has been terminated by an uncaught signal.
  560. *
  561. * It always returns false on Windows.
  562. *
  563. * @return bool
  564. *
  565. * @throws RuntimeException In case --enable-sigchild is activated
  566. * @throws LogicException In case the process is not terminated
  567. *
  568. * @api
  569. */
  570. public function hasBeenSignaled()
  571. {
  572. $this->requireProcessIsTerminated(__FUNCTION__);
  573. if ($this->isSigchildEnabled()) {
  574. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  575. }
  576. $this->updateStatus(false);
  577. return $this->processInformation['signaled'];
  578. }
  579. /**
  580. * Returns the number of the signal that caused the child process to terminate its execution.
  581. *
  582. * It is only meaningful if hasBeenSignaled() returns true.
  583. *
  584. * @return int
  585. *
  586. * @throws RuntimeException In case --enable-sigchild is activated
  587. * @throws LogicException In case the process is not terminated
  588. *
  589. * @api
  590. */
  591. public function getTermSignal()
  592. {
  593. $this->requireProcessIsTerminated(__FUNCTION__);
  594. if ($this->isSigchildEnabled()) {
  595. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  596. }
  597. $this->updateStatus(false);
  598. return $this->processInformation['termsig'];
  599. }
  600. /**
  601. * Returns true if the child process has been stopped by a signal.
  602. *
  603. * It always returns false on Windows.
  604. *
  605. * @return bool
  606. *
  607. * @throws LogicException In case the process is not terminated
  608. *
  609. * @api
  610. */
  611. public function hasBeenStopped()
  612. {
  613. $this->requireProcessIsTerminated(__FUNCTION__);
  614. $this->updateStatus(false);
  615. return $this->processInformation['stopped'];
  616. }
  617. /**
  618. * Returns the number of the signal that caused the child process to stop its execution.
  619. *
  620. * It is only meaningful if hasBeenStopped() returns true.
  621. *
  622. * @return int
  623. *
  624. * @throws LogicException In case the process is not terminated
  625. *
  626. * @api
  627. */
  628. public function getStopSignal()
  629. {
  630. $this->requireProcessIsTerminated(__FUNCTION__);
  631. $this->updateStatus(false);
  632. return $this->processInformation['stopsig'];
  633. }
  634. /**
  635. * Checks if the process is currently running.
  636. *
  637. * @return bool true if the process is currently running, false otherwise
  638. */
  639. public function isRunning()
  640. {
  641. if (self::STATUS_STARTED !== $this->status) {
  642. return false;
  643. }
  644. $this->updateStatus(false);
  645. return $this->processInformation['running'];
  646. }
  647. /**
  648. * Checks if the process has been started with no regard to the current state.
  649. *
  650. * @return bool true if status is ready, false otherwise
  651. */
  652. public function isStarted()
  653. {
  654. return $this->status != self::STATUS_READY;
  655. }
  656. /**
  657. * Checks if the process is terminated.
  658. *
  659. * @return bool true if process is terminated, false otherwise
  660. */
  661. public function isTerminated()
  662. {
  663. $this->updateStatus(false);
  664. return $this->status == self::STATUS_TERMINATED;
  665. }
  666. /**
  667. * Gets the process status.
  668. *
  669. * The status is one of: ready, started, terminated.
  670. *
  671. * @return string The current process status
  672. */
  673. public function getStatus()
  674. {
  675. $this->updateStatus(false);
  676. return $this->status;
  677. }
  678. /**
  679. * Stops the process.
  680. *
  681. * @param int|float $timeout The timeout in seconds
  682. * @param int $signal A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL
  683. *
  684. * @return int The exit-code of the process
  685. *
  686. * @throws RuntimeException if the process got signaled
  687. */
  688. public function stop($timeout = 10, $signal = null)
  689. {
  690. $timeoutMicro = microtime(true) + $timeout;
  691. if ($this->isRunning()) {
  692. if ('\\' === DIRECTORY_SEPARATOR && !$this->isSigchildEnabled()) {
  693. exec(sprintf("taskkill /F /T /PID %d 2>&1", $this->getPid()), $output, $exitCode);
  694. if ($exitCode > 0) {
  695. throw new RuntimeException('Unable to kill the process');
  696. }
  697. }
  698. // given `SIGTERM` may not be defined and that `proc_terminate` uses the constant value and not the constant itself, we use the same here
  699. $this->doSignal(15, false);
  700. do {
  701. usleep(1000);
  702. } while ($this->isRunning() && microtime(true) < $timeoutMicro);
  703. if ($this->isRunning() && !$this->isSigchildEnabled()) {
  704. if (null !== $signal || defined('SIGKILL')) {
  705. // avoid exception here :
  706. // process is supposed to be running, but it might have stop
  707. // just after this line.
  708. // in any case, let's silently discard the error, we can not do anything
  709. $this->doSignal($signal ?: SIGKILL, false);
  710. }
  711. }
  712. }
  713. $this->updateStatus(false);
  714. if ($this->processInformation['running']) {
  715. $this->close();
  716. }
  717. return $this->exitcode;
  718. }
  719. /**
  720. * Adds a line to the STDOUT stream.
  721. *
  722. * @param string $line The line to append
  723. */
  724. public function addOutput($line)
  725. {
  726. $this->lastOutputTime = microtime(true);
  727. $this->stdout .= $line;
  728. }
  729. /**
  730. * Adds a line to the STDERR stream.
  731. *
  732. * @param string $line The line to append
  733. */
  734. public function addErrorOutput($line)
  735. {
  736. $this->lastOutputTime = microtime(true);
  737. $this->stderr .= $line;
  738. }
  739. /**
  740. * Gets the command line to be executed.
  741. *
  742. * @return string The command to execute
  743. */
  744. public function getCommandLine()
  745. {
  746. return $this->commandline;
  747. }
  748. /**
  749. * Sets the command line to be executed.
  750. *
  751. * @param string $commandline The command to execute
  752. *
  753. * @return self The current Process instance
  754. */
  755. public function setCommandLine($commandline)
  756. {
  757. $this->commandline = $commandline;
  758. return $this;
  759. }
  760. /**
  761. * Gets the process timeout (max. runtime).
  762. *
  763. * @return float|null The timeout in seconds or null if it's disabled
  764. */
  765. public function getTimeout()
  766. {
  767. return $this->timeout;
  768. }
  769. /**
  770. * Gets the process idle timeout (max. time since last output).
  771. *
  772. * @return float|null The timeout in seconds or null if it's disabled
  773. */
  774. public function getIdleTimeout()
  775. {
  776. return $this->idleTimeout;
  777. }
  778. /**
  779. * Sets the process timeout (max. runtime).
  780. *
  781. * To disable the timeout, set this value to null.
  782. *
  783. * @param int|float|null $timeout The timeout in seconds
  784. *
  785. * @return self The current Process instance
  786. *
  787. * @throws InvalidArgumentException if the timeout is negative
  788. */
  789. public function setTimeout($timeout)
  790. {
  791. $this->timeout = $this->validateTimeout($timeout);
  792. return $this;
  793. }
  794. /**
  795. * Sets the process idle timeout (max. time since last output).
  796. *
  797. * To disable the timeout, set this value to null.
  798. *
  799. * @param int|float|null $timeout The timeout in seconds
  800. *
  801. * @return self The current Process instance.
  802. *
  803. * @throws LogicException if the output is disabled
  804. * @throws InvalidArgumentException if the timeout is negative
  805. */
  806. public function setIdleTimeout($timeout)
  807. {
  808. if (null !== $timeout && $this->outputDisabled) {
  809. throw new LogicException('Idle timeout can not be set while the output is disabled.');
  810. }
  811. $this->idleTimeout = $this->validateTimeout($timeout);
  812. return $this;
  813. }
  814. /**
  815. * Enables or disables the TTY mode.
  816. *
  817. * @param bool $tty True to enabled and false to disable
  818. *
  819. * @return self The current Process instance
  820. *
  821. * @throws RuntimeException In case the TTY mode is not supported
  822. */
  823. public function setTty($tty)
  824. {
  825. if ('\\' === DIRECTORY_SEPARATOR && $tty) {
  826. throw new RuntimeException('TTY mode is not supported on Windows platform.');
  827. }
  828. $this->tty = (bool) $tty;
  829. return $this;
  830. }
  831. /**
  832. * Checks if the TTY mode is enabled.
  833. *
  834. * @return bool true if the TTY mode is enabled, false otherwise
  835. */
  836. public function isTty()
  837. {
  838. return $this->tty;
  839. }
  840. /**
  841. * Sets PTY mode.
  842. *
  843. * @param bool $bool
  844. *
  845. * @return self
  846. */
  847. public function setPty($bool)
  848. {
  849. $this->pty = (bool) $bool;
  850. return $this;
  851. }
  852. /**
  853. * Returns PTY state.
  854. *
  855. * @return bool
  856. */
  857. public function isPty()
  858. {
  859. return $this->pty;
  860. }
  861. /**
  862. * Gets the working directory.
  863. *
  864. * @return string|null The current working directory or null on failure
  865. */
  866. public function getWorkingDirectory()
  867. {
  868. if (null === $this->cwd) {
  869. // getcwd() will return false if any one of the parent directories does not have
  870. // the readable or search mode set, even if the current directory does
  871. return getcwd() ?: null;
  872. }
  873. return $this->cwd;
  874. }
  875. /**
  876. * Sets the current working directory.
  877. *
  878. * @param string $cwd The new working directory
  879. *
  880. * @return self The current Process instance
  881. */
  882. public function setWorkingDirectory($cwd)
  883. {
  884. $this->cwd = $cwd;
  885. return $this;
  886. }
  887. /**
  888. * Gets the environment variables.
  889. *
  890. * @return array The current environment variables
  891. */
  892. public function getEnv()
  893. {
  894. return $this->env;
  895. }
  896. /**
  897. * Sets the environment variables.
  898. *
  899. * An environment variable value should be a string.
  900. * If it is an array, the variable is ignored.
  901. *
  902. * That happens in PHP when 'argv' is registered into
  903. * the $_ENV array for instance.
  904. *
  905. * @param array $env The new environment variables
  906. *
  907. * @return self The current Process instance
  908. */
  909. public function setEnv(array $env)
  910. {
  911. // Process can not handle env values that are arrays
  912. $env = array_filter($env, function ($value) {
  913. return !is_array($value);
  914. });
  915. $this->env = array();
  916. foreach ($env as $key => $value) {
  917. $this->env[(binary) $key] = (binary) $value;
  918. }
  919. return $this;
  920. }
  921. /**
  922. * Gets the contents of STDIN.
  923. *
  924. * @return string|null The current contents
  925. *
  926. * @deprecated Deprecated since version 2.5, to be removed in 3.0.
  927. * This method is deprecated in favor of getInput.
  928. */
  929. public function getStdin()
  930. {
  931. return $this->getInput();
  932. }
  933. /**
  934. * Gets the Process input.
  935. *
  936. * @return null|string The Process input
  937. */
  938. public function getInput()
  939. {
  940. return $this->input;
  941. }
  942. /**
  943. * Sets the contents of STDIN.
  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. if ('\\' === DIRECTORY_SEPARATOR) {
  1098. $this->processPipes = WindowsPipes::create($this, $this->input);
  1099. } else {
  1100. $this->processPipes = UnixPipes::create($this, $this->input);
  1101. }
  1102. $descriptors = $this->processPipes->getDescriptors($this->outputDisabled);
  1103. if (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  1104. // last exit code is output on the fourth pipe and caught to work around --enable-sigchild
  1105. $descriptors = array_merge($descriptors, array(array('pipe', 'w')));
  1106. $this->commandline = '('.$this->commandline.') 3>/dev/null; code=$?; echo $code >&3; exit $code';
  1107. }
  1108. return $descriptors;
  1109. }
  1110. /**
  1111. * Builds up the callback used by wait().
  1112. *
  1113. * The callbacks adds all occurred output to the specific buffer and calls
  1114. * the user callback (if present) with the received output.
  1115. *
  1116. * @param callable|null $callback The user defined PHP callback
  1117. *
  1118. * @return callable A PHP callable
  1119. */
  1120. protected function buildCallback($callback)
  1121. {
  1122. $that = $this;
  1123. $out = self::OUT;
  1124. $callback = function ($type, $data) use ($that, $callback, $out) {
  1125. if ($out == $type) {
  1126. $that->addOutput($data);
  1127. } else {
  1128. $that->addErrorOutput($data);
  1129. }
  1130. if (null !== $callback) {
  1131. call_user_func($callback, $type, $data);
  1132. }
  1133. };
  1134. return $callback;
  1135. }
  1136. /**
  1137. * Updates the status of the process, reads pipes.
  1138. *
  1139. * @param bool $blocking Whether to use a blocking read call.
  1140. */
  1141. protected function updateStatus($blocking)
  1142. {
  1143. if (self::STATUS_STARTED !== $this->status) {
  1144. return;
  1145. }
  1146. $this->processInformation = proc_get_status($this->process);
  1147. $this->captureExitCode();
  1148. $this->readPipes($blocking, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  1149. if (!$this->processInformation['running']) {
  1150. $this->close();
  1151. }
  1152. }
  1153. /**
  1154. * Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
  1155. *
  1156. * @return bool
  1157. */
  1158. protected function isSigchildEnabled()
  1159. {
  1160. if (null !== self::$sigchild) {
  1161. return self::$sigchild;
  1162. }
  1163. if (!function_exists('phpinfo')) {
  1164. return self::$sigchild = false;
  1165. }
  1166. ob_start();
  1167. phpinfo(INFO_GENERAL);
  1168. return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  1169. }
  1170. /**
  1171. * Validates and returns the filtered timeout.
  1172. *
  1173. * @param int|float|null $timeout
  1174. *
  1175. * @return float|null
  1176. *
  1177. * @throws InvalidArgumentException if the given timeout is a negative number
  1178. */
  1179. private function validateTimeout($timeout)
  1180. {
  1181. $timeout = (float) $timeout;
  1182. if (0.0 === $timeout) {
  1183. $timeout = null;
  1184. } elseif ($timeout < 0) {
  1185. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  1186. }
  1187. return $timeout;
  1188. }
  1189. /**
  1190. * Reads pipes, executes callback.
  1191. *
  1192. * @param bool $blocking Whether to use blocking calls or not.
  1193. * @param bool $close Whether to close file handles or not.
  1194. */
  1195. private function readPipes($blocking, $close)
  1196. {
  1197. $result = $this->processPipes->readAndWrite($blocking, $close);
  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. }