Process.php 54 KB

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