Process.php 44 KB

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