Process.php 52 KB

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