Drupal investigation

Process.php 45KB

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