Process.php 53 KB

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