Process.php 51 KB

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