Process.php 51 KB

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