Process.php 54 KB

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