Process.php 52 KB

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