Process.php 52 KB

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