Process.php 51 KB

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