Process.php 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  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 += $this->env;
  277. }
  278. $env += $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) {
  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. public function getIterator(int $flags = 0)
  546. {
  547. $this->readPipesForOutput(__FUNCTION__, false);
  548. $clearOutput = !(self::ITER_KEEP_OUTPUT & $flags);
  549. $blocking = !(self::ITER_NON_BLOCKING & $flags);
  550. $yieldOut = !(self::ITER_SKIP_OUT & $flags);
  551. $yieldErr = !(self::ITER_SKIP_ERR & $flags);
  552. while (null !== $this->callback || ($yieldOut && !feof($this->stdout)) || ($yieldErr && !feof($this->stderr))) {
  553. if ($yieldOut) {
  554. $out = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
  555. if (isset($out[0])) {
  556. if ($clearOutput) {
  557. $this->clearOutput();
  558. } else {
  559. $this->incrementalOutputOffset = ftell($this->stdout);
  560. }
  561. yield self::OUT => $out;
  562. }
  563. }
  564. if ($yieldErr) {
  565. $err = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
  566. if (isset($err[0])) {
  567. if ($clearOutput) {
  568. $this->clearErrorOutput();
  569. } else {
  570. $this->incrementalErrorOutputOffset = ftell($this->stderr);
  571. }
  572. yield self::ERR => $err;
  573. }
  574. }
  575. if (!$blocking && !isset($out[0]) && !isset($err[0])) {
  576. yield self::OUT => '';
  577. }
  578. $this->checkTimeout();
  579. $this->readPipesForOutput(__FUNCTION__, $blocking);
  580. }
  581. }
  582. /**
  583. * Clears the process output.
  584. *
  585. * @return $this
  586. */
  587. public function clearOutput()
  588. {
  589. ftruncate($this->stdout, 0);
  590. fseek($this->stdout, 0);
  591. $this->incrementalOutputOffset = 0;
  592. return $this;
  593. }
  594. /**
  595. * Returns the current error output of the process (STDERR).
  596. *
  597. * @return string The process error output
  598. *
  599. * @throws LogicException in case the output has been disabled
  600. * @throws LogicException In case the process is not started
  601. */
  602. public function getErrorOutput()
  603. {
  604. $this->readPipesForOutput(__FUNCTION__);
  605. if (false === $ret = stream_get_contents($this->stderr, -1, 0)) {
  606. return '';
  607. }
  608. return $ret;
  609. }
  610. /**
  611. * Returns the errorOutput incrementally.
  612. *
  613. * In comparison with the getErrorOutput method which always return the
  614. * whole error output, this one returns the new error output since the last
  615. * call.
  616. *
  617. * @return string The process error output since the last call
  618. *
  619. * @throws LogicException in case the output has been disabled
  620. * @throws LogicException In case the process is not started
  621. */
  622. public function getIncrementalErrorOutput()
  623. {
  624. $this->readPipesForOutput(__FUNCTION__);
  625. $latest = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
  626. $this->incrementalErrorOutputOffset = ftell($this->stderr);
  627. if (false === $latest) {
  628. return '';
  629. }
  630. return $latest;
  631. }
  632. /**
  633. * Clears the process output.
  634. *
  635. * @return $this
  636. */
  637. public function clearErrorOutput()
  638. {
  639. ftruncate($this->stderr, 0);
  640. fseek($this->stderr, 0);
  641. $this->incrementalErrorOutputOffset = 0;
  642. return $this;
  643. }
  644. /**
  645. * Returns the exit code returned by the process.
  646. *
  647. * @return int|null The exit status code, null if the Process is not terminated
  648. */
  649. public function getExitCode()
  650. {
  651. $this->updateStatus(false);
  652. return $this->exitcode;
  653. }
  654. /**
  655. * Returns a string representation for the exit code returned by the process.
  656. *
  657. * This method relies on the Unix exit code status standardization
  658. * and might not be relevant for other operating systems.
  659. *
  660. * @return string|null A string representation for the exit status code, null if the Process is not terminated
  661. *
  662. * @see http://tldp.org/LDP/abs/html/exitcodes.html
  663. * @see http://en.wikipedia.org/wiki/Unix_signal
  664. */
  665. public function getExitCodeText()
  666. {
  667. if (null === $exitcode = $this->getExitCode()) {
  668. return null;
  669. }
  670. return self::$exitCodes[$exitcode] ?? 'Unknown error';
  671. }
  672. /**
  673. * Checks if the process ended successfully.
  674. *
  675. * @return bool true if the process ended successfully, false otherwise
  676. */
  677. public function isSuccessful()
  678. {
  679. return 0 === $this->getExitCode();
  680. }
  681. /**
  682. * Returns true if the child process has been terminated by an uncaught signal.
  683. *
  684. * It always returns false on Windows.
  685. *
  686. * @return bool
  687. *
  688. * @throws LogicException In case the process is not terminated
  689. */
  690. public function hasBeenSignaled()
  691. {
  692. $this->requireProcessIsTerminated(__FUNCTION__);
  693. return $this->processInformation['signaled'];
  694. }
  695. /**
  696. * Returns the number of the signal that caused the child process to terminate its execution.
  697. *
  698. * It is only meaningful if hasBeenSignaled() returns true.
  699. *
  700. * @return int
  701. *
  702. * @throws RuntimeException In case --enable-sigchild is activated
  703. * @throws LogicException In case the process is not terminated
  704. */
  705. public function getTermSignal()
  706. {
  707. $this->requireProcessIsTerminated(__FUNCTION__);
  708. if ($this->isSigchildEnabled() && -1 === $this->processInformation['termsig']) {
  709. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  710. }
  711. return $this->processInformation['termsig'];
  712. }
  713. /**
  714. * Returns true if the child process has been stopped by a signal.
  715. *
  716. * It always returns false on Windows.
  717. *
  718. * @return bool
  719. *
  720. * @throws LogicException In case the process is not terminated
  721. */
  722. public function hasBeenStopped()
  723. {
  724. $this->requireProcessIsTerminated(__FUNCTION__);
  725. return $this->processInformation['stopped'];
  726. }
  727. /**
  728. * Returns the number of the signal that caused the child process to stop its execution.
  729. *
  730. * It is only meaningful if hasBeenStopped() returns true.
  731. *
  732. * @return int
  733. *
  734. * @throws LogicException In case the process is not terminated
  735. */
  736. public function getStopSignal()
  737. {
  738. $this->requireProcessIsTerminated(__FUNCTION__);
  739. return $this->processInformation['stopsig'];
  740. }
  741. /**
  742. * Checks if the process is currently running.
  743. *
  744. * @return bool true if the process is currently running, false otherwise
  745. */
  746. public function isRunning()
  747. {
  748. if (self::STATUS_STARTED !== $this->status) {
  749. return false;
  750. }
  751. $this->updateStatus(false);
  752. return $this->processInformation['running'];
  753. }
  754. /**
  755. * Checks if the process has been started with no regard to the current state.
  756. *
  757. * @return bool true if status is ready, false otherwise
  758. */
  759. public function isStarted()
  760. {
  761. return self::STATUS_READY != $this->status;
  762. }
  763. /**
  764. * Checks if the process is terminated.
  765. *
  766. * @return bool true if process is terminated, false otherwise
  767. */
  768. public function isTerminated()
  769. {
  770. $this->updateStatus(false);
  771. return self::STATUS_TERMINATED == $this->status;
  772. }
  773. /**
  774. * Gets the process status.
  775. *
  776. * The status is one of: ready, started, terminated.
  777. *
  778. * @return string The current process status
  779. */
  780. public function getStatus()
  781. {
  782. $this->updateStatus(false);
  783. return $this->status;
  784. }
  785. /**
  786. * Stops the process.
  787. *
  788. * @param int|float $timeout The timeout in seconds
  789. * @param int $signal A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL (9)
  790. *
  791. * @return int|null The exit-code of the process or null if it's not running
  792. */
  793. public function stop(float $timeout = 10, int $signal = null)
  794. {
  795. $timeoutMicro = microtime(true) + $timeout;
  796. if ($this->isRunning()) {
  797. // given SIGTERM may not be defined and that "proc_terminate" uses the constant value and not the constant itself, we use the same here
  798. $this->doSignal(15, false);
  799. do {
  800. usleep(1000);
  801. } while ($this->isRunning() && microtime(true) < $timeoutMicro);
  802. if ($this->isRunning()) {
  803. // Avoid exception here: process is supposed to be running, but it might have stopped just
  804. // after this line. In any case, let's silently discard the error, we cannot do anything.
  805. $this->doSignal($signal ?: 9, false);
  806. }
  807. }
  808. if ($this->isRunning()) {
  809. if (isset($this->fallbackStatus['pid'])) {
  810. unset($this->fallbackStatus['pid']);
  811. return $this->stop(0, $signal);
  812. }
  813. $this->close();
  814. }
  815. return $this->exitcode;
  816. }
  817. /**
  818. * Adds a line to the STDOUT stream.
  819. *
  820. * @internal
  821. */
  822. public function addOutput(string $line)
  823. {
  824. $this->lastOutputTime = microtime(true);
  825. fseek($this->stdout, 0, \SEEK_END);
  826. fwrite($this->stdout, $line);
  827. fseek($this->stdout, $this->incrementalOutputOffset);
  828. }
  829. /**
  830. * Adds a line to the STDERR stream.
  831. *
  832. * @internal
  833. */
  834. public function addErrorOutput(string $line)
  835. {
  836. $this->lastOutputTime = microtime(true);
  837. fseek($this->stderr, 0, \SEEK_END);
  838. fwrite($this->stderr, $line);
  839. fseek($this->stderr, $this->incrementalErrorOutputOffset);
  840. }
  841. /**
  842. * Gets the last output time in seconds.
  843. *
  844. * @return float|null The last output time in seconds or null if it isn't started
  845. */
  846. public function getLastOutputTime(): ?float
  847. {
  848. return $this->lastOutputTime;
  849. }
  850. /**
  851. * Gets the command line to be executed.
  852. *
  853. * @return string The command to execute
  854. */
  855. public function getCommandLine()
  856. {
  857. return \is_array($this->commandline) ? implode(' ', array_map([$this, 'escapeArgument'], $this->commandline)) : $this->commandline;
  858. }
  859. /**
  860. * Gets the process timeout (max. runtime).
  861. *
  862. * @return float|null The timeout in seconds or null if it's disabled
  863. */
  864. public function getTimeout()
  865. {
  866. return $this->timeout;
  867. }
  868. /**
  869. * Gets the process idle timeout (max. time since last output).
  870. *
  871. * @return float|null The timeout in seconds or null if it's disabled
  872. */
  873. public function getIdleTimeout()
  874. {
  875. return $this->idleTimeout;
  876. }
  877. /**
  878. * Sets the process timeout (max. runtime) in seconds.
  879. *
  880. * To disable the timeout, set this value to null.
  881. *
  882. * @return $this
  883. *
  884. * @throws InvalidArgumentException if the timeout is negative
  885. */
  886. public function setTimeout(?float $timeout)
  887. {
  888. $this->timeout = $this->validateTimeout($timeout);
  889. return $this;
  890. }
  891. /**
  892. * Sets the process idle timeout (max. time since last output) in seconds.
  893. *
  894. * To disable the timeout, set this value to null.
  895. *
  896. * @return $this
  897. *
  898. * @throws LogicException if the output is disabled
  899. * @throws InvalidArgumentException if the timeout is negative
  900. */
  901. public function setIdleTimeout(?float $timeout)
  902. {
  903. if (null !== $timeout && $this->outputDisabled) {
  904. throw new LogicException('Idle timeout can not be set while the output is disabled.');
  905. }
  906. $this->idleTimeout = $this->validateTimeout($timeout);
  907. return $this;
  908. }
  909. /**
  910. * Enables or disables the TTY mode.
  911. *
  912. * @return $this
  913. *
  914. * @throws RuntimeException In case the TTY mode is not supported
  915. */
  916. public function setTty(bool $tty)
  917. {
  918. if ('\\' === \DIRECTORY_SEPARATOR && $tty) {
  919. throw new RuntimeException('TTY mode is not supported on Windows platform.');
  920. }
  921. if ($tty && !self::isTtySupported()) {
  922. throw new RuntimeException('TTY mode requires /dev/tty to be read/writable.');
  923. }
  924. $this->tty = $tty;
  925. return $this;
  926. }
  927. /**
  928. * Checks if the TTY mode is enabled.
  929. *
  930. * @return bool true if the TTY mode is enabled, false otherwise
  931. */
  932. public function isTty()
  933. {
  934. return $this->tty;
  935. }
  936. /**
  937. * Sets PTY mode.
  938. *
  939. * @return $this
  940. */
  941. public function setPty(bool $bool)
  942. {
  943. $this->pty = $bool;
  944. return $this;
  945. }
  946. /**
  947. * Returns PTY state.
  948. *
  949. * @return bool
  950. */
  951. public function isPty()
  952. {
  953. return $this->pty;
  954. }
  955. /**
  956. * Gets the working directory.
  957. *
  958. * @return string|null The current working directory or null on failure
  959. */
  960. public function getWorkingDirectory()
  961. {
  962. if (null === $this->cwd) {
  963. // getcwd() will return false if any one of the parent directories does not have
  964. // the readable or search mode set, even if the current directory does
  965. return getcwd() ?: null;
  966. }
  967. return $this->cwd;
  968. }
  969. /**
  970. * Sets the current working directory.
  971. *
  972. * @return $this
  973. */
  974. public function setWorkingDirectory(string $cwd)
  975. {
  976. $this->cwd = $cwd;
  977. return $this;
  978. }
  979. /**
  980. * Gets the environment variables.
  981. *
  982. * @return array The current environment variables
  983. */
  984. public function getEnv()
  985. {
  986. return $this->env;
  987. }
  988. /**
  989. * Sets the environment variables.
  990. *
  991. * Each environment variable value should be a string.
  992. * If it is an array, the variable is ignored.
  993. * If it is false or null, it will be removed when
  994. * env vars are otherwise inherited.
  995. *
  996. * That happens in PHP when 'argv' is registered into
  997. * the $_ENV array for instance.
  998. *
  999. * @param array $env The new environment variables
  1000. *
  1001. * @return $this
  1002. */
  1003. public function setEnv(array $env)
  1004. {
  1005. // Process can not handle env values that are arrays
  1006. $env = array_filter($env, function ($value) {
  1007. return !\is_array($value);
  1008. });
  1009. $this->env = $env;
  1010. return $this;
  1011. }
  1012. /**
  1013. * Gets the Process input.
  1014. *
  1015. * @return resource|string|\Iterator|null The Process input
  1016. */
  1017. public function getInput()
  1018. {
  1019. return $this->input;
  1020. }
  1021. /**
  1022. * Sets the input.
  1023. *
  1024. * This content will be passed to the underlying process standard input.
  1025. *
  1026. * @param string|int|float|bool|resource|\Traversable|null $input The content
  1027. *
  1028. * @return $this
  1029. *
  1030. * @throws LogicException In case the process is running
  1031. */
  1032. public function setInput($input)
  1033. {
  1034. if ($this->isRunning()) {
  1035. throw new LogicException('Input can not be set while the process is running.');
  1036. }
  1037. $this->input = ProcessUtils::validateInput(__METHOD__, $input);
  1038. return $this;
  1039. }
  1040. /**
  1041. * Performs a check between the timeout definition and the time the process started.
  1042. *
  1043. * In case you run a background process (with the start method), you should
  1044. * trigger this method regularly to ensure the process timeout
  1045. *
  1046. * @throws ProcessTimedOutException In case the timeout was reached
  1047. */
  1048. public function checkTimeout()
  1049. {
  1050. if (self::STATUS_STARTED !== $this->status) {
  1051. return;
  1052. }
  1053. if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
  1054. $this->stop(0);
  1055. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL);
  1056. }
  1057. if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
  1058. $this->stop(0);
  1059. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE);
  1060. }
  1061. }
  1062. /**
  1063. * @throws LogicException in case process is not started
  1064. */
  1065. public function getStartTime(): float
  1066. {
  1067. if (!$this->isStarted()) {
  1068. throw new LogicException('Start time is only available after process start.');
  1069. }
  1070. return $this->starttime;
  1071. }
  1072. /**
  1073. * Defines options to pass to the underlying proc_open().
  1074. *
  1075. * @see https://php.net/proc_open for the options supported by PHP.
  1076. *
  1077. * Enabling the "create_new_console" option allows a subprocess to continue
  1078. * to run after the main process exited, on both Windows and *nix
  1079. */
  1080. public function setOptions(array $options)
  1081. {
  1082. if ($this->isRunning()) {
  1083. throw new RuntimeException('Setting options while the process is running is not possible.');
  1084. }
  1085. $defaultOptions = $this->options;
  1086. $existingOptions = ['blocking_pipes', 'create_process_group', 'create_new_console'];
  1087. foreach ($options as $key => $value) {
  1088. if (!\in_array($key, $existingOptions)) {
  1089. $this->options = $defaultOptions;
  1090. throw new LogicException(sprintf('Invalid option "%s" passed to "%s()". Supported options are "%s".', $key, __METHOD__, implode('", "', $existingOptions)));
  1091. }
  1092. $this->options[$key] = $value;
  1093. }
  1094. }
  1095. /**
  1096. * Returns whether TTY is supported on the current operating system.
  1097. */
  1098. public static function isTtySupported(): bool
  1099. {
  1100. static $isTtySupported;
  1101. if (null === $isTtySupported) {
  1102. $isTtySupported = (bool) @proc_open('echo 1 >/dev/null', [['file', '/dev/tty', 'r'], ['file', '/dev/tty', 'w'], ['file', '/dev/tty', 'w']], $pipes);
  1103. }
  1104. return $isTtySupported;
  1105. }
  1106. /**
  1107. * Returns whether PTY is supported on the current operating system.
  1108. *
  1109. * @return bool
  1110. */
  1111. public static function isPtySupported()
  1112. {
  1113. static $result;
  1114. if (null !== $result) {
  1115. return $result;
  1116. }
  1117. if ('\\' === \DIRECTORY_SEPARATOR) {
  1118. return $result = false;
  1119. }
  1120. return $result = (bool) @proc_open('echo 1 >/dev/null', [['pty'], ['pty'], ['pty']], $pipes);
  1121. }
  1122. /**
  1123. * Creates the descriptors needed by the proc_open.
  1124. */
  1125. private function getDescriptors(): array
  1126. {
  1127. if ($this->input instanceof \Iterator) {
  1128. $this->input->rewind();
  1129. }
  1130. if ('\\' === \DIRECTORY_SEPARATOR) {
  1131. $this->processPipes = new WindowsPipes($this->input, !$this->outputDisabled || $this->hasCallback);
  1132. } else {
  1133. $this->processPipes = new UnixPipes($this->isTty(), $this->isPty(), $this->input, !$this->outputDisabled || $this->hasCallback);
  1134. }
  1135. return $this->processPipes->getDescriptors();
  1136. }
  1137. /**
  1138. * Builds up the callback used by wait().
  1139. *
  1140. * The callbacks adds all occurred output to the specific buffer and calls
  1141. * the user callback (if present) with the received output.
  1142. *
  1143. * @param callable|null $callback The user defined PHP callback
  1144. *
  1145. * @return \Closure A PHP closure
  1146. */
  1147. protected function buildCallback(callable $callback = null)
  1148. {
  1149. if ($this->outputDisabled) {
  1150. return function ($type, $data) use ($callback): bool {
  1151. return null !== $callback && $callback($type, $data);
  1152. };
  1153. }
  1154. $out = self::OUT;
  1155. return function ($type, $data) use ($callback, $out): bool {
  1156. if ($out == $type) {
  1157. $this->addOutput($data);
  1158. } else {
  1159. $this->addErrorOutput($data);
  1160. }
  1161. return null !== $callback && $callback($type, $data);
  1162. };
  1163. }
  1164. /**
  1165. * Updates the status of the process, reads pipes.
  1166. *
  1167. * @param bool $blocking Whether to use a blocking read call
  1168. */
  1169. protected function updateStatus(bool $blocking)
  1170. {
  1171. if (self::STATUS_STARTED !== $this->status) {
  1172. return;
  1173. }
  1174. $this->processInformation = proc_get_status($this->process);
  1175. $running = $this->processInformation['running'];
  1176. $this->readPipes($running && $blocking, '\\' !== \DIRECTORY_SEPARATOR || !$running);
  1177. if ($this->fallbackStatus && $this->isSigchildEnabled()) {
  1178. $this->processInformation = $this->fallbackStatus + $this->processInformation;
  1179. }
  1180. if (!$running) {
  1181. $this->close();
  1182. }
  1183. }
  1184. /**
  1185. * Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
  1186. *
  1187. * @return bool
  1188. */
  1189. protected function isSigchildEnabled()
  1190. {
  1191. if (null !== self::$sigchild) {
  1192. return self::$sigchild;
  1193. }
  1194. if (!\function_exists('phpinfo')) {
  1195. return self::$sigchild = false;
  1196. }
  1197. ob_start();
  1198. phpinfo(\INFO_GENERAL);
  1199. return self::$sigchild = str_contains(ob_get_clean(), '--enable-sigchild');
  1200. }
  1201. /**
  1202. * Reads pipes for the freshest output.
  1203. *
  1204. * @param string $caller The name of the method that needs fresh outputs
  1205. * @param bool $blocking Whether to use blocking calls or not
  1206. *
  1207. * @throws LogicException in case output has been disabled or process is not started
  1208. */
  1209. private function readPipesForOutput(string $caller, bool $blocking = false)
  1210. {
  1211. if ($this->outputDisabled) {
  1212. throw new LogicException('Output has been disabled.');
  1213. }
  1214. $this->requireProcessIsStarted($caller);
  1215. $this->updateStatus($blocking);
  1216. }
  1217. /**
  1218. * Validates and returns the filtered timeout.
  1219. *
  1220. * @throws InvalidArgumentException if the given timeout is a negative number
  1221. */
  1222. private function validateTimeout(?float $timeout): ?float
  1223. {
  1224. $timeout = (float) $timeout;
  1225. if (0.0 === $timeout) {
  1226. $timeout = null;
  1227. } elseif ($timeout < 0) {
  1228. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  1229. }
  1230. return $timeout;
  1231. }
  1232. /**
  1233. * Reads pipes, executes callback.
  1234. *
  1235. * @param bool $blocking Whether to use blocking calls or not
  1236. * @param bool $close Whether to close file handles or not
  1237. */
  1238. private function readPipes(bool $blocking, bool $close)
  1239. {
  1240. $result = $this->processPipes->readAndWrite($blocking, $close);
  1241. $callback = $this->callback;
  1242. foreach ($result as $type => $data) {
  1243. if (3 !== $type) {
  1244. $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data);
  1245. } elseif (!isset($this->fallbackStatus['signaled'])) {
  1246. $this->fallbackStatus['exitcode'] = (int) $data;
  1247. }
  1248. }
  1249. }
  1250. /**
  1251. * Closes process resource, closes file handles, sets the exitcode.
  1252. *
  1253. * @return int The exitcode
  1254. */
  1255. private function close(): int
  1256. {
  1257. $this->processPipes->close();
  1258. if (\is_resource($this->process)) {
  1259. proc_close($this->process);
  1260. }
  1261. $this->exitcode = $this->processInformation['exitcode'];
  1262. $this->status = self::STATUS_TERMINATED;
  1263. if (-1 === $this->exitcode) {
  1264. if ($this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
  1265. // if process has been signaled, no exitcode but a valid termsig, apply Unix convention
  1266. $this->exitcode = 128 + $this->processInformation['termsig'];
  1267. } elseif ($this->isSigchildEnabled()) {
  1268. $this->processInformation['signaled'] = true;
  1269. $this->processInformation['termsig'] = -1;
  1270. }
  1271. }
  1272. // Free memory from self-reference callback created by buildCallback
  1273. // Doing so in other contexts like __destruct or by garbage collector is ineffective
  1274. // Now pipes are closed, so the callback is no longer necessary
  1275. $this->callback = null;
  1276. return $this->exitcode;
  1277. }
  1278. /**
  1279. * Resets data related to the latest run of the process.
  1280. */
  1281. private function resetProcessData()
  1282. {
  1283. $this->starttime = null;
  1284. $this->callback = null;
  1285. $this->exitcode = null;
  1286. $this->fallbackStatus = [];
  1287. $this->processInformation = null;
  1288. $this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+');
  1289. $this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+');
  1290. $this->process = null;
  1291. $this->latestSignal = null;
  1292. $this->status = self::STATUS_READY;
  1293. $this->incrementalOutputOffset = 0;
  1294. $this->incrementalErrorOutputOffset = 0;
  1295. }
  1296. /**
  1297. * Sends a POSIX signal to the process.
  1298. *
  1299. * @param int $signal A valid POSIX signal (see https://php.net/pcntl.constants)
  1300. * @param bool $throwException Whether to throw exception in case signal failed
  1301. *
  1302. * @return bool True if the signal was sent successfully, false otherwise
  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('Can not 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. $cmd = 'cmd /V:ON /E:ON /D /C ('.str_replace("\n", ' ', $cmd).')';
  1380. foreach ($this->processPipes->getFiles() as $offset => $filename) {
  1381. $cmd .= ' '.$offset.'>"'.$filename.'"';
  1382. }
  1383. return $cmd;
  1384. }
  1385. /**
  1386. * Ensures the process is running or terminated, throws a LogicException if the process has a not started.
  1387. *
  1388. * @throws LogicException if the process has not run
  1389. */
  1390. private function requireProcessIsStarted(string $functionName)
  1391. {
  1392. if (!$this->isStarted()) {
  1393. throw new LogicException(sprintf('Process must be started before calling "%s()".', $functionName));
  1394. }
  1395. }
  1396. /**
  1397. * Ensures the process is terminated, throws a LogicException if the process has a status different than "terminated".
  1398. *
  1399. * @throws LogicException if the process is not yet terminated
  1400. */
  1401. private function requireProcessIsTerminated(string $functionName)
  1402. {
  1403. if (!$this->isTerminated()) {
  1404. throw new LogicException(sprintf('Process must be terminated before calling "%s()".', $functionName));
  1405. }
  1406. }
  1407. /**
  1408. * Escapes a string to be used as a shell argument.
  1409. */
  1410. private function escapeArgument(?string $argument): string
  1411. {
  1412. if ('' === $argument || null === $argument) {
  1413. return '""';
  1414. }
  1415. if ('\\' !== \DIRECTORY_SEPARATOR) {
  1416. return "'".str_replace("'", "'\\''", $argument)."'";
  1417. }
  1418. if (str_contains($argument, "\0")) {
  1419. $argument = str_replace("\0", '?', $argument);
  1420. }
  1421. if (!preg_match('/[\/()%!^"<>&|\s]/', $argument)) {
  1422. return $argument;
  1423. }
  1424. $argument = preg_replace('/(\\\\+)$/', '$1$1', $argument);
  1425. return '"'.str_replace(['"', '^', '%', '!', "\n"], ['""', '"^^"', '"^%"', '"^!"', '!LF!'], $argument).'"';
  1426. }
  1427. private function replacePlaceholders(string $commandline, array $env)
  1428. {
  1429. return preg_replace_callback('/"\$\{:([_a-zA-Z]++[_a-zA-Z0-9]*+)\}"/', function ($matches) use ($commandline, $env) {
  1430. if (!isset($env[$matches[1]]) || false === $env[$matches[1]]) {
  1431. throw new InvalidArgumentException(sprintf('Command line is missing a value for parameter "%s": ', $matches[1]).$commandline);
  1432. }
  1433. return $this->escapeArgument($env[$matches[1]]);
  1434. }, $commandline);
  1435. }
  1436. private function getDefaultEnv(): array
  1437. {
  1438. $env = [];
  1439. foreach ($_SERVER as $k => $v) {
  1440. if (\is_string($v) && false !== $v = getenv($k)) {
  1441. $env[$k] = $v;
  1442. }
  1443. }
  1444. foreach ($_ENV as $k => $v) {
  1445. if (\is_string($v)) {
  1446. $env[$k] = $v;
  1447. }
  1448. }
  1449. return $env;
  1450. }
  1451. }