Process.php 51 KB

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