Process.php 51 KB

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