暫無描述

Process.php 52KB

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