Process.php 50 KB

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