Process.php 51 KB

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