Process.php 45 KB

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