Process.php 38 KB

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