Process.php 55 KB

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