Process.php 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652
  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('The provided cwd does not exist.');
  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. usleep(1000);
  371. }
  372. if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {
  373. throw new ProcessSignaledException($this);
  374. }
  375. return $this->exitcode;
  376. }
  377. /**
  378. * Waits until the callback returns true.
  379. *
  380. * The callback receives the type of output (out or err) and some bytes
  381. * from the output in real-time while writing the standard input to the process.
  382. * It allows to have feedback from the independent process during execution.
  383. *
  384. * @throws RuntimeException When process timed out
  385. * @throws LogicException When process is not yet started
  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 http://www.php.net/manual/en/pcntl.constants.php)
  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;
  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 The exit-code of the process
  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 self The current Process instance
  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).
  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 self The current Process instance
  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 self The current Process instance
  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 self The current Process instance
  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 self
  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 self The current Process instance
  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 self The current Process instance
  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 self The current Process instance
  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 self The current Process instance
  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) {
  1135. if (null !== $callback) {
  1136. return $callback($type, $data);
  1137. }
  1138. };
  1139. }
  1140. $out = self::OUT;
  1141. return function ($type, $data) use ($callback, $out) {
  1142. if ($out == $type) {
  1143. $this->addOutput($data);
  1144. } else {
  1145. $this->addErrorOutput($data);
  1146. }
  1147. if (null !== $callback) {
  1148. return $callback($type, $data);
  1149. }
  1150. };
  1151. }
  1152. /**
  1153. * Updates the status of the process, reads pipes.
  1154. *
  1155. * @param bool $blocking Whether to use a blocking read call
  1156. */
  1157. protected function updateStatus($blocking)
  1158. {
  1159. if (self::STATUS_STARTED !== $this->status) {
  1160. return;
  1161. }
  1162. $this->processInformation = proc_get_status($this->process);
  1163. $running = $this->processInformation['running'];
  1164. $this->readPipes($running && $blocking, '\\' !== \DIRECTORY_SEPARATOR || !$running);
  1165. if ($this->fallbackStatus && $this->isSigchildEnabled()) {
  1166. $this->processInformation = $this->fallbackStatus + $this->processInformation;
  1167. }
  1168. if (!$running) {
  1169. $this->close();
  1170. }
  1171. }
  1172. /**
  1173. * Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
  1174. *
  1175. * @return bool
  1176. */
  1177. protected function isSigchildEnabled()
  1178. {
  1179. if (null !== self::$sigchild) {
  1180. return self::$sigchild;
  1181. }
  1182. if (!\function_exists('phpinfo')) {
  1183. return self::$sigchild = false;
  1184. }
  1185. ob_start();
  1186. phpinfo(INFO_GENERAL);
  1187. return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  1188. }
  1189. /**
  1190. * Reads pipes for the freshest output.
  1191. *
  1192. * @param string $caller The name of the method that needs fresh outputs
  1193. * @param bool $blocking Whether to use blocking calls or not
  1194. *
  1195. * @throws LogicException in case output has been disabled or process is not started
  1196. */
  1197. private function readPipesForOutput(string $caller, bool $blocking = false)
  1198. {
  1199. if ($this->outputDisabled) {
  1200. throw new LogicException('Output has been disabled.');
  1201. }
  1202. $this->requireProcessIsStarted($caller);
  1203. $this->updateStatus($blocking);
  1204. }
  1205. /**
  1206. * Validates and returns the filtered timeout.
  1207. *
  1208. * @throws InvalidArgumentException if the given timeout is a negative number
  1209. */
  1210. private function validateTimeout(?float $timeout): ?float
  1211. {
  1212. $timeout = (float) $timeout;
  1213. if (0.0 === $timeout) {
  1214. $timeout = null;
  1215. } elseif ($timeout < 0) {
  1216. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  1217. }
  1218. return $timeout;
  1219. }
  1220. /**
  1221. * Reads pipes, executes callback.
  1222. *
  1223. * @param bool $blocking Whether to use blocking calls or not
  1224. * @param bool $close Whether to close file handles or not
  1225. */
  1226. private function readPipes(bool $blocking, bool $close)
  1227. {
  1228. $result = $this->processPipes->readAndWrite($blocking, $close);
  1229. $callback = $this->callback;
  1230. foreach ($result as $type => $data) {
  1231. if (3 !== $type) {
  1232. $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data);
  1233. } elseif (!isset($this->fallbackStatus['signaled'])) {
  1234. $this->fallbackStatus['exitcode'] = (int) $data;
  1235. }
  1236. }
  1237. }
  1238. /**
  1239. * Closes process resource, closes file handles, sets the exitcode.
  1240. *
  1241. * @return int The exitcode
  1242. */
  1243. private function close(): int
  1244. {
  1245. $this->processPipes->close();
  1246. if (\is_resource($this->process)) {
  1247. proc_close($this->process);
  1248. }
  1249. $this->exitcode = $this->processInformation['exitcode'];
  1250. $this->status = self::STATUS_TERMINATED;
  1251. if (-1 === $this->exitcode) {
  1252. if ($this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
  1253. // if process has been signaled, no exitcode but a valid termsig, apply Unix convention
  1254. $this->exitcode = 128 + $this->processInformation['termsig'];
  1255. } elseif ($this->isSigchildEnabled()) {
  1256. $this->processInformation['signaled'] = true;
  1257. $this->processInformation['termsig'] = -1;
  1258. }
  1259. }
  1260. // Free memory from self-reference callback created by buildCallback
  1261. // Doing so in other contexts like __destruct or by garbage collector is ineffective
  1262. // Now pipes are closed, so the callback is no longer necessary
  1263. $this->callback = null;
  1264. return $this->exitcode;
  1265. }
  1266. /**
  1267. * Resets data related to the latest run of the process.
  1268. */
  1269. private function resetProcessData()
  1270. {
  1271. $this->starttime = null;
  1272. $this->callback = null;
  1273. $this->exitcode = null;
  1274. $this->fallbackStatus = [];
  1275. $this->processInformation = null;
  1276. $this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+b');
  1277. $this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+b');
  1278. $this->process = null;
  1279. $this->latestSignal = null;
  1280. $this->status = self::STATUS_READY;
  1281. $this->incrementalOutputOffset = 0;
  1282. $this->incrementalErrorOutputOffset = 0;
  1283. }
  1284. /**
  1285. * Sends a POSIX signal to the process.
  1286. *
  1287. * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
  1288. * @param bool $throwException Whether to throw exception in case signal failed
  1289. *
  1290. * @return bool True if the signal was sent successfully, false otherwise
  1291. *
  1292. * @throws LogicException In case the process is not running
  1293. * @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed
  1294. * @throws RuntimeException In case of failure
  1295. */
  1296. private function doSignal(int $signal, bool $throwException): bool
  1297. {
  1298. if (null === $pid = $this->getPid()) {
  1299. if ($throwException) {
  1300. throw new LogicException('Can not send signal on a non running process.');
  1301. }
  1302. return false;
  1303. }
  1304. if ('\\' === \DIRECTORY_SEPARATOR) {
  1305. exec(sprintf('taskkill /F /T /PID %d 2>&1', $pid), $output, $exitCode);
  1306. if ($exitCode && $this->isRunning()) {
  1307. if ($throwException) {
  1308. throw new RuntimeException(sprintf('Unable to kill the process (%s).', implode(' ', $output)));
  1309. }
  1310. return false;
  1311. }
  1312. } else {
  1313. if (!$this->isSigchildEnabled()) {
  1314. $ok = @proc_terminate($this->process, $signal);
  1315. } elseif (\function_exists('posix_kill')) {
  1316. $ok = @posix_kill($pid, $signal);
  1317. } elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), [2 => ['pipe', 'w']], $pipes)) {
  1318. $ok = false === fgets($pipes[2]);
  1319. }
  1320. if (!$ok) {
  1321. if ($throwException) {
  1322. throw new RuntimeException(sprintf('Error while sending signal "%s".', $signal));
  1323. }
  1324. return false;
  1325. }
  1326. }
  1327. $this->latestSignal = $signal;
  1328. $this->fallbackStatus['signaled'] = true;
  1329. $this->fallbackStatus['exitcode'] = -1;
  1330. $this->fallbackStatus['termsig'] = $this->latestSignal;
  1331. return true;
  1332. }
  1333. private function prepareWindowsCommandLine(string $cmd, array &$env)
  1334. {
  1335. $uid = uniqid('', true);
  1336. $varCount = 0;
  1337. $varCache = [];
  1338. $cmd = preg_replace_callback(
  1339. '/"(?:(
  1340. [^"%!^]*+
  1341. (?:
  1342. (?: !LF! | "(?:\^[%!^])?+" )
  1343. [^"%!^]*+
  1344. )++
  1345. ) | [^"]*+ )"/x',
  1346. function ($m) use (&$env, &$varCache, &$varCount, $uid) {
  1347. if (!isset($m[1])) {
  1348. return $m[0];
  1349. }
  1350. if (isset($varCache[$m[0]])) {
  1351. return $varCache[$m[0]];
  1352. }
  1353. if (false !== strpos($value = $m[1], "\0")) {
  1354. $value = str_replace("\0", '?', $value);
  1355. }
  1356. if (false === strpbrk($value, "\"%!\n")) {
  1357. return '"'.$value.'"';
  1358. }
  1359. $value = str_replace(['!LF!', '"^!"', '"^%"', '"^^"', '""'], ["\n", '!', '%', '^', '"'], $value);
  1360. $value = '"'.preg_replace('/(\\\\*)"/', '$1$1\\"', $value).'"';
  1361. $var = $uid.++$varCount;
  1362. $env[$var] = $value;
  1363. return $varCache[$m[0]] = '!'.$var.'!';
  1364. },
  1365. $cmd
  1366. );
  1367. $cmd = 'cmd /V:ON /E:ON /D /C ('.str_replace("\n", ' ', $cmd).')';
  1368. foreach ($this->processPipes->getFiles() as $offset => $filename) {
  1369. $cmd .= ' '.$offset.'>"'.$filename.'"';
  1370. }
  1371. return $cmd;
  1372. }
  1373. /**
  1374. * Ensures the process is running or terminated, throws a LogicException if the process has a not started.
  1375. *
  1376. * @throws LogicException if the process has not run
  1377. */
  1378. private function requireProcessIsStarted(string $functionName)
  1379. {
  1380. if (!$this->isStarted()) {
  1381. throw new LogicException(sprintf('Process must be started before calling %s.', $functionName));
  1382. }
  1383. }
  1384. /**
  1385. * Ensures the process is terminated, throws a LogicException if the process has a status different than "terminated".
  1386. *
  1387. * @throws LogicException if the process is not yet terminated
  1388. */
  1389. private function requireProcessIsTerminated(string $functionName)
  1390. {
  1391. if (!$this->isTerminated()) {
  1392. throw new LogicException(sprintf('Process must be terminated before calling %s.', $functionName));
  1393. }
  1394. }
  1395. /**
  1396. * Escapes a string to be used as a shell argument.
  1397. */
  1398. private function escapeArgument(?string $argument): string
  1399. {
  1400. if ('' === $argument || null === $argument) {
  1401. return '""';
  1402. }
  1403. if ('\\' !== \DIRECTORY_SEPARATOR) {
  1404. return "'".str_replace("'", "'\\''", $argument)."'";
  1405. }
  1406. if (false !== strpos($argument, "\0")) {
  1407. $argument = str_replace("\0", '?', $argument);
  1408. }
  1409. if (!preg_match('/[\/()%!^"<>&|\s]/', $argument)) {
  1410. return $argument;
  1411. }
  1412. $argument = preg_replace('/(\\\\+)$/', '$1$1', $argument);
  1413. return '"'.str_replace(['"', '^', '%', '!', "\n"], ['""', '"^^"', '"^%"', '"^!"', '!LF!'], $argument).'"';
  1414. }
  1415. private function getDefaultEnv()
  1416. {
  1417. $env = [];
  1418. foreach ($_SERVER as $k => $v) {
  1419. if (\is_string($v) && false !== $v = getenv($k)) {
  1420. $env[$k] = $v;
  1421. }
  1422. }
  1423. foreach ($_ENV as $k => $v) {
  1424. if (\is_string($v)) {
  1425. $env[$k] = $v;
  1426. }
  1427. }
  1428. return $env;
  1429. }
  1430. }