Process.php 48 KB

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