Process.php 55 KB

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