Process.php 47 KB

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