Process.php 52 KB

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