Process.php 52 KB

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