Process.php 51 KB

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