Process.php 50 KB

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