PageRenderTime 47ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/symfony/src/Symfony/Component/Process/Process.php

https://github.com/silvanei/treinaweb-symfony2-basico
PHP | 1312 lines | 600 code | 171 blank | 541 comment | 81 complexity | e395db460f28bff62498cab76b119bb1 MD5 | raw file
Possible License(s): BSD-3-Clause
  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\ProcessTimedOutException;
  14. use Symfony\Component\Process\Exception\RuntimeException;
  15. /**
  16. * Process is a thin wrapper around proc_* functions to easily
  17. * start independent PHP processes.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. *
  21. * @api
  22. */
  23. class Process
  24. {
  25. const ERR = 'err';
  26. const OUT = 'out';
  27. const STATUS_READY = 'ready';
  28. const STATUS_STARTED = 'started';
  29. const STATUS_TERMINATED = 'terminated';
  30. const STDIN = 0;
  31. const STDOUT = 1;
  32. const STDERR = 2;
  33. // Timeout Precision in seconds.
  34. const TIMEOUT_PRECISION = 0.2;
  35. private $callback;
  36. private $commandline;
  37. private $cwd;
  38. private $env;
  39. private $stdin;
  40. private $starttime;
  41. private $lastOutputTime;
  42. private $timeout;
  43. private $idleTimeout;
  44. private $options;
  45. private $exitcode;
  46. private $fallbackExitcode;
  47. private $processInformation;
  48. private $stdout;
  49. private $stderr;
  50. private $enhanceWindowsCompatibility = true;
  51. private $enhanceSigchildCompatibility;
  52. private $process;
  53. private $status = self::STATUS_READY;
  54. private $incrementalOutputOffset = 0;
  55. private $incrementalErrorOutputOffset = 0;
  56. private $tty;
  57. private $useFileHandles = false;
  58. /** @var ProcessPipes */
  59. private $processPipes;
  60. private static $sigchild;
  61. /**
  62. * Exit codes translation table.
  63. *
  64. * User-defined errors must use exit codes in the 64-113 range.
  65. *
  66. * @var array
  67. */
  68. public static $exitCodes = array(
  69. 0 => 'OK',
  70. 1 => 'General error',
  71. 2 => 'Misuse of shell builtins',
  72. 126 => 'Invoked command cannot execute',
  73. 127 => 'Command not found',
  74. 128 => 'Invalid exit argument',
  75. // signals
  76. 129 => 'Hangup',
  77. 130 => 'Interrupt',
  78. 131 => 'Quit and dump core',
  79. 132 => 'Illegal instruction',
  80. 133 => 'Trace/breakpoint trap',
  81. 134 => 'Process aborted',
  82. 135 => 'Bus error: "access to undefined portion of memory object"',
  83. 136 => 'Floating point exception: "erroneous arithmetic operation"',
  84. 137 => 'Kill (terminate immediately)',
  85. 138 => 'User-defined 1',
  86. 139 => 'Segmentation violation',
  87. 140 => 'User-defined 2',
  88. 141 => 'Write to pipe with no one reading',
  89. 142 => 'Signal raised by alarm',
  90. 143 => 'Termination (request to terminate)',
  91. // 144 - not defined
  92. 145 => 'Child process terminated, stopped (or continued*)',
  93. 146 => 'Continue if stopped',
  94. 147 => 'Stop executing temporarily',
  95. 148 => 'Terminal stop signal',
  96. 149 => 'Background process attempting to read from tty ("in")',
  97. 150 => 'Background process attempting to write to tty ("out")',
  98. 151 => 'Urgent data available on socket',
  99. 152 => 'CPU time limit exceeded',
  100. 153 => 'File size limit exceeded',
  101. 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
  102. 155 => 'Profiling timer expired',
  103. // 156 - not defined
  104. 157 => 'Pollable event',
  105. // 158 - not defined
  106. 159 => 'Bad syscall',
  107. );
  108. /**
  109. * Constructor.
  110. *
  111. * @param string $commandline The command line to run
  112. * @param string|null $cwd The working directory or null to use the working dir of the current PHP process
  113. * @param array|null $env The environment variables or null to inherit
  114. * @param string|null $stdin The STDIN content
  115. * @param int|float|null $timeout The timeout in seconds or null to disable
  116. * @param array $options An array of options for proc_open
  117. *
  118. * @throws RuntimeException When proc_open is not installed
  119. *
  120. * @api
  121. */
  122. public function __construct($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array())
  123. {
  124. if (!function_exists('proc_open')) {
  125. throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
  126. }
  127. $this->commandline = $commandline;
  128. $this->cwd = $cwd;
  129. // on Windows, if the cwd changed via chdir(), proc_open defaults to the dir where PHP was started
  130. // on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected
  131. // @see : https://bugs.php.net/bug.php?id=51800
  132. // @see : https://bugs.php.net/bug.php?id=50524
  133. if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || defined('PHP_WINDOWS_VERSION_BUILD'))) {
  134. $this->cwd = getcwd();
  135. }
  136. if (null !== $env) {
  137. $this->setEnv($env);
  138. }
  139. $this->stdin = $stdin;
  140. $this->setTimeout($timeout);
  141. $this->useFileHandles = defined('PHP_WINDOWS_VERSION_BUILD');
  142. $this->enhanceSigchildCompatibility = !defined('PHP_WINDOWS_VERSION_BUILD') && $this->isSigchildEnabled();
  143. $this->options = array_replace(array('suppress_errors' => true, 'binary_pipes' => true), $options);
  144. }
  145. public function __destruct()
  146. {
  147. // stop() will check if we have a process running.
  148. $this->stop();
  149. }
  150. public function __clone()
  151. {
  152. $this->resetProcessData();
  153. }
  154. /**
  155. * Runs the process.
  156. *
  157. * The callback receives the type of output (out or err) and
  158. * some bytes from the output in real-time. It allows to have feedback
  159. * from the independent process during execution.
  160. *
  161. * The STDOUT and STDERR are also available after the process is finished
  162. * via the getOutput() and getErrorOutput() methods.
  163. *
  164. * @param callable|null $callback A PHP callback to run whenever there is some
  165. * output available on STDOUT or STDERR
  166. *
  167. * @return int The exit status code
  168. *
  169. * @throws RuntimeException When process can't be launched
  170. * @throws RuntimeException When process stopped after receiving signal
  171. *
  172. * @api
  173. */
  174. public function run($callback = null)
  175. {
  176. $this->start($callback);
  177. return $this->wait();
  178. }
  179. /**
  180. * Starts the process and returns after sending the STDIN.
  181. *
  182. * This method blocks until all STDIN data is sent to the process then it
  183. * returns while the process runs in the background.
  184. *
  185. * The termination of the process can be awaited with wait().
  186. *
  187. * The callback receives the type of output (out or err) and some bytes from
  188. * the output in real-time while writing the standard input to the process.
  189. * It allows to have feedback from the independent process during execution.
  190. * If there is no callback passed, the wait() method can be called
  191. * with true as a second parameter then the callback will get all data occurred
  192. * in (and since) the start call.
  193. *
  194. * @param callable|null $callback A PHP callback to run whenever there is some
  195. * output available on STDOUT or STDERR
  196. *
  197. * @return Process The process itself
  198. *
  199. * @throws RuntimeException When process can't be launched
  200. * @throws RuntimeException When process is already running
  201. */
  202. public function start($callback = null)
  203. {
  204. if ($this->isRunning()) {
  205. throw new RuntimeException('Process is already running');
  206. }
  207. $this->resetProcessData();
  208. $this->starttime = $this->lastOutputTime = microtime(true);
  209. $this->callback = $this->buildCallback($callback);
  210. $descriptors = $this->getDescriptors();
  211. $commandline = $this->commandline;
  212. if (defined('PHP_WINDOWS_VERSION_BUILD') && $this->enhanceWindowsCompatibility) {
  213. $commandline = 'cmd /V:ON /E:ON /C "('.$commandline.')';
  214. foreach ($this->processPipes->getFiles() as $offset => $filename) {
  215. $commandline .= ' '.$offset.'>'.ProcessUtils::escapeArgument($filename);
  216. }
  217. $commandline .= '"';
  218. if (!isset($this->options['bypass_shell'])) {
  219. $this->options['bypass_shell'] = true;
  220. }
  221. }
  222. $this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $this->env, $this->options);
  223. if (!is_resource($this->process)) {
  224. throw new RuntimeException('Unable to launch a new process.');
  225. }
  226. $this->status = self::STATUS_STARTED;
  227. $this->processPipes->unblock();
  228. if ($this->tty) {
  229. return;
  230. }
  231. $this->processPipes->write(false, $this->stdin);
  232. $this->updateStatus(false);
  233. $this->checkTimeout();
  234. }
  235. /**
  236. * Restarts the process.
  237. *
  238. * Be warned that the process is cloned before being started.
  239. *
  240. * @param callable|null $callback A PHP callback to run whenever there is some
  241. * output available on STDOUT or STDERR
  242. *
  243. * @return Process The new process
  244. *
  245. * @throws RuntimeException When process can't be launched
  246. * @throws RuntimeException When process is already running
  247. *
  248. * @see start()
  249. */
  250. public function restart($callback = null)
  251. {
  252. if ($this->isRunning()) {
  253. throw new RuntimeException('Process is already running');
  254. }
  255. $process = clone $this;
  256. $process->start($callback);
  257. return $process;
  258. }
  259. /**
  260. * Waits for the process to terminate.
  261. *
  262. * The callback receives the type of output (out or err) and some bytes
  263. * from the output in real-time while writing the standard input to the process.
  264. * It allows to have feedback from the independent process during execution.
  265. *
  266. * @param callable|null $callback A valid PHP callback
  267. *
  268. * @return int The exitcode of the process
  269. *
  270. * @throws RuntimeException When process timed out
  271. * @throws RuntimeException When process stopped after receiving signal
  272. * @throws LogicException When process is not yet started
  273. */
  274. public function wait($callback = null)
  275. {
  276. $this->requireProcessIsStarted(__FUNCTION__);
  277. $this->updateStatus(false);
  278. if (null !== $callback) {
  279. $this->callback = $this->buildCallback($callback);
  280. }
  281. do {
  282. $this->checkTimeout();
  283. $running = defined('PHP_WINDOWS_VERSION_BUILD') ? $this->isRunning() : $this->processPipes->hasOpenHandles();
  284. $close = !defined('PHP_WINDOWS_VERSION_BUILD') || !$running;;
  285. $this->readPipes(true, $close);
  286. } while ($running);
  287. while ($this->isRunning()) {
  288. usleep(1000);
  289. }
  290. if ($this->processInformation['signaled']) {
  291. throw new RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig']));
  292. }
  293. return $this->exitcode;
  294. }
  295. /**
  296. * Returns the Pid (process identifier), if applicable.
  297. *
  298. * @return int|null The process id if running, null otherwise
  299. *
  300. * @throws RuntimeException In case --enable-sigchild is activated
  301. */
  302. public function getPid()
  303. {
  304. if ($this->isSigchildEnabled()) {
  305. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved.');
  306. }
  307. $this->updateStatus(false);
  308. return $this->isRunning() ? $this->processInformation['pid'] : null;
  309. }
  310. /**
  311. * Sends a POSIX signal to the process.
  312. *
  313. * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
  314. *
  315. * @return Process
  316. *
  317. * @throws LogicException In case the process is not running
  318. * @throws RuntimeException In case --enable-sigchild is activated
  319. * @throws RuntimeException In case of failure
  320. */
  321. public function signal($signal)
  322. {
  323. $this->doSignal($signal, true);
  324. return $this;
  325. }
  326. /**
  327. * Returns the current output of the process (STDOUT).
  328. *
  329. * @return string The process output
  330. *
  331. * @throws LogicException In case the process is not started
  332. *
  333. * @api
  334. */
  335. public function getOutput()
  336. {
  337. $this->requireProcessIsStarted(__FUNCTION__);
  338. $this->readPipes(false, defined('PHP_WINDOWS_VERSION_BUILD') ? !$this->processInformation['running'] : true);
  339. return $this->stdout;
  340. }
  341. /**
  342. * Returns the output incrementally.
  343. *
  344. * In comparison with the getOutput method which always return the whole
  345. * output, this one returns the new output since the last call.
  346. *
  347. * @throws LogicException In case the process is not started
  348. *
  349. * @return string The process output since the last call
  350. */
  351. public function getIncrementalOutput()
  352. {
  353. $this->requireProcessIsStarted(__FUNCTION__);
  354. $data = $this->getOutput();
  355. $latest = substr($data, $this->incrementalOutputOffset);
  356. $this->incrementalOutputOffset = strlen($data);
  357. return $latest;
  358. }
  359. /**
  360. * Clears the process output.
  361. *
  362. * @return Process
  363. */
  364. public function clearOutput()
  365. {
  366. $this->stdout = '';
  367. $this->incrementalOutputOffset = 0;
  368. return $this;
  369. }
  370. /**
  371. * Returns the current error output of the process (STDERR).
  372. *
  373. * @return string The process error output
  374. *
  375. * @throws LogicException In case the process is not started
  376. *
  377. * @api
  378. */
  379. public function getErrorOutput()
  380. {
  381. $this->requireProcessIsStarted(__FUNCTION__);
  382. $this->readPipes(false, defined('PHP_WINDOWS_VERSION_BUILD') ? !$this->processInformation['running'] : true);
  383. return $this->stderr;
  384. }
  385. /**
  386. * Returns the errorOutput incrementally.
  387. *
  388. * In comparison with the getErrorOutput method which always return the
  389. * whole error output, this one returns the new error output since the last
  390. * call.
  391. *
  392. * @throws LogicException In case the process is not started
  393. *
  394. * @return string The process error output since the last call
  395. */
  396. public function getIncrementalErrorOutput()
  397. {
  398. $this->requireProcessIsStarted(__FUNCTION__);
  399. $data = $this->getErrorOutput();
  400. $latest = substr($data, $this->incrementalErrorOutputOffset);
  401. $this->incrementalErrorOutputOffset = strlen($data);
  402. return $latest;
  403. }
  404. /**
  405. * Clears the process output.
  406. *
  407. * @return Process
  408. */
  409. public function clearErrorOutput()
  410. {
  411. $this->stderr = '';
  412. $this->incrementalErrorOutputOffset = 0;
  413. return $this;
  414. }
  415. /**
  416. * Returns the exit code returned by the process.
  417. *
  418. * @return null|int The exit status code, null if the Process is not terminated
  419. *
  420. * @throws RuntimeException In case --enable-sigchild is activated and the sigchild compatibility mode is disabled
  421. *
  422. * @api
  423. */
  424. public function getExitCode()
  425. {
  426. if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
  427. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
  428. }
  429. $this->updateStatus(false);
  430. return $this->exitcode;
  431. }
  432. /**
  433. * Returns a string representation for the exit code returned by the process.
  434. *
  435. * This method relies on the Unix exit code status standardization
  436. * and might not be relevant for other operating systems.
  437. *
  438. * @return null|string A string representation for the exit status code, null if the Process is not terminated.
  439. *
  440. * @throws RuntimeException In case --enable-sigchild is activated and the sigchild compatibility mode is disabled
  441. *
  442. * @see http://tldp.org/LDP/abs/html/exitcodes.html
  443. * @see http://en.wikipedia.org/wiki/Unix_signal
  444. */
  445. public function getExitCodeText()
  446. {
  447. if (null === $exitcode = $this->getExitCode()) {
  448. return;
  449. }
  450. return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
  451. }
  452. /**
  453. * Checks if the process ended successfully.
  454. *
  455. * @return bool true if the process ended successfully, false otherwise
  456. *
  457. * @api
  458. */
  459. public function isSuccessful()
  460. {
  461. return 0 === $this->getExitCode();
  462. }
  463. /**
  464. * Returns true if the child process has been terminated by an uncaught signal.
  465. *
  466. * It always returns false on Windows.
  467. *
  468. * @return bool
  469. *
  470. * @throws RuntimeException In case --enable-sigchild is activated
  471. * @throws LogicException In case the process is not terminated
  472. *
  473. * @api
  474. */
  475. public function hasBeenSignaled()
  476. {
  477. $this->requireProcessIsTerminated(__FUNCTION__);
  478. if ($this->isSigchildEnabled()) {
  479. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  480. }
  481. $this->updateStatus(false);
  482. return $this->processInformation['signaled'];
  483. }
  484. /**
  485. * Returns the number of the signal that caused the child process to terminate its execution.
  486. *
  487. * It is only meaningful if hasBeenSignaled() returns true.
  488. *
  489. * @return int
  490. *
  491. * @throws RuntimeException In case --enable-sigchild is activated
  492. * @throws LogicException In case the process is not terminated
  493. *
  494. * @api
  495. */
  496. public function getTermSignal()
  497. {
  498. $this->requireProcessIsTerminated(__FUNCTION__);
  499. if ($this->isSigchildEnabled()) {
  500. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  501. }
  502. $this->updateStatus(false);
  503. return $this->processInformation['termsig'];
  504. }
  505. /**
  506. * Returns true if the child process has been stopped by a signal.
  507. *
  508. * It always returns false on Windows.
  509. *
  510. * @return bool
  511. *
  512. * @throws LogicException In case the process is not terminated
  513. *
  514. * @api
  515. */
  516. public function hasBeenStopped()
  517. {
  518. $this->requireProcessIsTerminated(__FUNCTION__);
  519. $this->updateStatus(false);
  520. return $this->processInformation['stopped'];
  521. }
  522. /**
  523. * Returns the number of the signal that caused the child process to stop its execution.
  524. *
  525. * It is only meaningful if hasBeenStopped() returns true.
  526. *
  527. * @return int
  528. *
  529. * @throws LogicException In case the process is not terminated
  530. *
  531. * @api
  532. */
  533. public function getStopSignal()
  534. {
  535. $this->requireProcessIsTerminated(__FUNCTION__);
  536. $this->updateStatus(false);
  537. return $this->processInformation['stopsig'];
  538. }
  539. /**
  540. * Checks if the process is currently running.
  541. *
  542. * @return bool true if the process is currently running, false otherwise
  543. */
  544. public function isRunning()
  545. {
  546. if (self::STATUS_STARTED !== $this->status) {
  547. return false;
  548. }
  549. $this->updateStatus(false);
  550. return $this->processInformation['running'];
  551. }
  552. /**
  553. * Checks if the process has been started with no regard to the current state.
  554. *
  555. * @return bool true if status is ready, false otherwise
  556. */
  557. public function isStarted()
  558. {
  559. return $this->status != self::STATUS_READY;
  560. }
  561. /**
  562. * Checks if the process is terminated.
  563. *
  564. * @return bool true if process is terminated, false otherwise
  565. */
  566. public function isTerminated()
  567. {
  568. $this->updateStatus(false);
  569. return $this->status == self::STATUS_TERMINATED;
  570. }
  571. /**
  572. * Gets the process status.
  573. *
  574. * The status is one of: ready, started, terminated.
  575. *
  576. * @return string The current process status
  577. */
  578. public function getStatus()
  579. {
  580. $this->updateStatus(false);
  581. return $this->status;
  582. }
  583. /**
  584. * Stops the process.
  585. *
  586. * @param int|float $timeout The timeout in seconds
  587. * @param int $signal A POSIX signal to send in case the process has not stop at timeout, default is SIGKILL
  588. *
  589. * @return int The exit-code of the process
  590. *
  591. * @throws RuntimeException if the process got signaled
  592. */
  593. public function stop($timeout = 10, $signal = null)
  594. {
  595. $timeoutMicro = microtime(true) + $timeout;
  596. if ($this->isRunning()) {
  597. if (defined('PHP_WINDOWS_VERSION_BUILD') && !$this->isSigchildEnabled()) {
  598. exec(sprintf("taskkill /F /T /PID %d 2>&1", $this->getPid()), $output, $exitCode);
  599. if ($exitCode > 0) {
  600. throw new RuntimeException('Unable to kill the process');
  601. }
  602. }
  603. proc_terminate($this->process);
  604. do {
  605. usleep(1000);
  606. } while ($this->isRunning() && microtime(true) < $timeoutMicro);
  607. if ($this->isRunning() && !$this->isSigchildEnabled()) {
  608. if (null !== $signal || defined('SIGKILL')) {
  609. // avoid exception here :
  610. // process is supposed to be running, but it might have stop
  611. // just after this line.
  612. // in any case, let's silently discard the error, we can not do anything
  613. $this->doSignal($signal ?: SIGKILL, false);
  614. }
  615. }
  616. }
  617. $this->updateStatus(false);
  618. if ($this->processInformation['running']) {
  619. $this->close();
  620. }
  621. return $this->exitcode;
  622. }
  623. /**
  624. * Adds a line to the STDOUT stream.
  625. *
  626. * @param string $line The line to append
  627. */
  628. public function addOutput($line)
  629. {
  630. $this->lastOutputTime = microtime(true);
  631. $this->stdout .= $line;
  632. }
  633. /**
  634. * Adds a line to the STDERR stream.
  635. *
  636. * @param string $line The line to append
  637. */
  638. public function addErrorOutput($line)
  639. {
  640. $this->lastOutputTime = microtime(true);
  641. $this->stderr .= $line;
  642. }
  643. /**
  644. * Gets the command line to be executed.
  645. *
  646. * @return string The command to execute
  647. */
  648. public function getCommandLine()
  649. {
  650. return $this->commandline;
  651. }
  652. /**
  653. * Sets the command line to be executed.
  654. *
  655. * @param string $commandline The command to execute
  656. *
  657. * @return self The current Process instance
  658. */
  659. public function setCommandLine($commandline)
  660. {
  661. $this->commandline = $commandline;
  662. return $this;
  663. }
  664. /**
  665. * Gets the process timeout (max. runtime).
  666. *
  667. * @return float|null The timeout in seconds or null if it's disabled
  668. */
  669. public function getTimeout()
  670. {
  671. return $this->timeout;
  672. }
  673. /**
  674. * Gets the process idle timeout (max. time since last output).
  675. *
  676. * @return float|null The timeout in seconds or null if it's disabled
  677. */
  678. public function getIdleTimeout()
  679. {
  680. return $this->idleTimeout;
  681. }
  682. /**
  683. * Sets the process timeout (max. runtime).
  684. *
  685. * To disable the timeout, set this value to null.
  686. *
  687. * @param int|float|null $timeout The timeout in seconds
  688. *
  689. * @return self The current Process instance
  690. *
  691. * @throws InvalidArgumentException if the timeout is negative
  692. */
  693. public function setTimeout($timeout)
  694. {
  695. $this->timeout = $this->validateTimeout($timeout);
  696. return $this;
  697. }
  698. /**
  699. * Sets the process idle timeout (max. time since last output).
  700. *
  701. * To disable the timeout, set this value to null.
  702. *
  703. * @param int|float|null $timeout The timeout in seconds
  704. *
  705. * @return self The current Process instance.
  706. *
  707. * @throws InvalidArgumentException if the timeout is negative
  708. */
  709. public function setIdleTimeout($timeout)
  710. {
  711. $this->idleTimeout = $this->validateTimeout($timeout);
  712. return $this;
  713. }
  714. /**
  715. * Enables or disables the TTY mode.
  716. *
  717. * @param bool $tty True to enabled and false to disable
  718. *
  719. * @return self The current Process instance
  720. *
  721. * @throws RuntimeException In case the TTY mode is not supported
  722. */
  723. public function setTty($tty)
  724. {
  725. if (defined('PHP_WINDOWS_VERSION_BUILD') && $tty) {
  726. throw new RuntimeException('TTY mode is not supported on Windows platform.');
  727. }
  728. $this->tty = (bool) $tty;
  729. return $this;
  730. }
  731. /**
  732. * Checks if the TTY mode is enabled.
  733. *
  734. * @return bool true if the TTY mode is enabled, false otherwise
  735. */
  736. public function isTty()
  737. {
  738. return $this->tty;
  739. }
  740. /**
  741. * Gets the working directory.
  742. *
  743. * @return string|null The current working directory or null on failure
  744. */
  745. public function getWorkingDirectory()
  746. {
  747. if (null === $this->cwd) {
  748. // getcwd() will return false if any one of the parent directories does not have
  749. // the readable or search mode set, even if the current directory does
  750. return getcwd() ?: null;
  751. }
  752. return $this->cwd;
  753. }
  754. /**
  755. * Sets the current working directory.
  756. *
  757. * @param string $cwd The new working directory
  758. *
  759. * @return self The current Process instance
  760. */
  761. public function setWorkingDirectory($cwd)
  762. {
  763. $this->cwd = $cwd;
  764. return $this;
  765. }
  766. /**
  767. * Gets the environment variables.
  768. *
  769. * @return array The current environment variables
  770. */
  771. public function getEnv()
  772. {
  773. return $this->env;
  774. }
  775. /**
  776. * Sets the environment variables.
  777. *
  778. * An environment variable value should be a string.
  779. * If it is an array, the variable is ignored.
  780. *
  781. * That happens in PHP when 'argv' is registered into
  782. * the $_ENV array for instance.
  783. *
  784. * @param array $env The new environment variables
  785. *
  786. * @return self The current Process instance
  787. */
  788. public function setEnv(array $env)
  789. {
  790. // Process can not handle env values that are arrays
  791. $env = array_filter($env, function ($value) {
  792. return !is_array($value);
  793. });
  794. $this->env = array();
  795. foreach ($env as $key => $value) {
  796. $this->env[(binary) $key] = (binary) $value;
  797. }
  798. return $this;
  799. }
  800. /**
  801. * Gets the contents of STDIN.
  802. *
  803. * @return string|null The current contents
  804. */
  805. public function getStdin()
  806. {
  807. return $this->stdin;
  808. }
  809. /**
  810. * Sets the contents of STDIN.
  811. *
  812. * @param string|null $stdin The new contents
  813. *
  814. * @return self The current Process instance
  815. *
  816. * @throws LogicException In case the process is running
  817. */
  818. public function setStdin($stdin)
  819. {
  820. if ($this->isRunning()) {
  821. throw new LogicException('STDIN can not be set while the process is running.');
  822. }
  823. $this->stdin = $stdin;
  824. return $this;
  825. }
  826. /**
  827. * Gets the options for proc_open.
  828. *
  829. * @return array The current options
  830. */
  831. public function getOptions()
  832. {
  833. return $this->options;
  834. }
  835. /**
  836. * Sets the options for proc_open.
  837. *
  838. * @param array $options The new options
  839. *
  840. * @return self The current Process instance
  841. */
  842. public function setOptions(array $options)
  843. {
  844. $this->options = $options;
  845. return $this;
  846. }
  847. /**
  848. * Gets whether or not Windows compatibility is enabled.
  849. *
  850. * This is true by default.
  851. *
  852. * @return bool
  853. */
  854. public function getEnhanceWindowsCompatibility()
  855. {
  856. return $this->enhanceWindowsCompatibility;
  857. }
  858. /**
  859. * Sets whether or not Windows compatibility is enabled.
  860. *
  861. * @param bool $enhance
  862. *
  863. * @return self The current Process instance
  864. */
  865. public function setEnhanceWindowsCompatibility($enhance)
  866. {
  867. $this->enhanceWindowsCompatibility = (bool) $enhance;
  868. return $this;
  869. }
  870. /**
  871. * Returns whether sigchild compatibility mode is activated or not.
  872. *
  873. * @return bool
  874. */
  875. public function getEnhanceSigchildCompatibility()
  876. {
  877. return $this->enhanceSigchildCompatibility;
  878. }
  879. /**
  880. * Activates sigchild compatibility mode.
  881. *
  882. * Sigchild compatibility mode is required to get the exit code and
  883. * determine the success of a process when PHP has been compiled with
  884. * the --enable-sigchild option
  885. *
  886. * @param bool $enhance
  887. *
  888. * @return self The current Process instance
  889. */
  890. public function setEnhanceSigchildCompatibility($enhance)
  891. {
  892. $this->enhanceSigchildCompatibility = (bool) $enhance;
  893. return $this;
  894. }
  895. /**
  896. * Performs a check between the timeout definition and the time the process started.
  897. *
  898. * In case you run a background process (with the start method), you should
  899. * trigger this method regularly to ensure the process timeout
  900. *
  901. * @throws ProcessTimedOutException In case the timeout was reached
  902. */
  903. public function checkTimeout()
  904. {
  905. if ($this->status !== self::STATUS_STARTED) {
  906. return;
  907. }
  908. if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
  909. $this->stop(0);
  910. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL);
  911. }
  912. if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
  913. $this->stop(0);
  914. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE);
  915. }
  916. }
  917. /**
  918. * Creates the descriptors needed by the proc_open.
  919. *
  920. * @return array
  921. */
  922. private function getDescriptors()
  923. {
  924. $this->processPipes = new ProcessPipes($this->useFileHandles, $this->tty);
  925. $descriptors = $this->processPipes->getDescriptors();
  926. if (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  927. // last exit code is output on the fourth pipe and caught to work around --enable-sigchild
  928. $descriptors = array_merge($descriptors, array(array('pipe', 'w')));
  929. $this->commandline = '('.$this->commandline.') 3>/dev/null; code=$?; echo $code >&3; exit $code';
  930. }
  931. return $descriptors;
  932. }
  933. /**
  934. * Builds up the callback used by wait().
  935. *
  936. * The callbacks adds all occurred output to the specific buffer and calls
  937. * the user callback (if present) with the received output.
  938. *
  939. * @param callable|null $callback The user defined PHP callback
  940. *
  941. * @return callable A PHP callable
  942. */
  943. protected function buildCallback($callback)
  944. {
  945. $that = $this;
  946. $out = self::OUT;
  947. $err = self::ERR;
  948. $callback = function ($type, $data) use ($that, $callback, $out, $err) {
  949. if ($out == $type) {
  950. $that->addOutput($data);
  951. } else {
  952. $that->addErrorOutput($data);
  953. }
  954. if (null !== $callback) {
  955. call_user_func($callback, $type, $data);
  956. }
  957. };
  958. return $callback;
  959. }
  960. /**
  961. * Updates the status of the process, reads pipes.
  962. *
  963. * @param bool $blocking Whether to use a blocking read call.
  964. */
  965. protected function updateStatus($blocking)
  966. {
  967. if (self::STATUS_STARTED !== $this->status) {
  968. return;
  969. }
  970. $this->processInformation = proc_get_status($this->process);
  971. $this->captureExitCode();
  972. $this->readPipes($blocking, defined('PHP_WINDOWS_VERSION_BUILD') ? !$this->processInformation['running'] : true);
  973. if (!$this->processInformation['running']) {
  974. $this->close();
  975. }
  976. }
  977. /**
  978. * Returns whether PHP has been compiled with the '--enable-sigchild' option or not.
  979. *
  980. * @return bool
  981. */
  982. protected function isSigchildEnabled()
  983. {
  984. if (null !== self::$sigchild) {
  985. return self::$sigchild;
  986. }
  987. if (!function_exists('phpinfo')) {
  988. return self::$sigchild = false;
  989. }
  990. ob_start();
  991. phpinfo(INFO_GENERAL);
  992. return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  993. }
  994. /**
  995. * Validates and returns the filtered timeout.
  996. *
  997. * @param int|float|null $timeout
  998. *
  999. * @return float|null
  1000. */
  1001. private function validateTimeout($timeout)
  1002. {
  1003. $timeout = (float) $timeout;
  1004. if (0.0 === $timeout) {
  1005. $timeout = null;
  1006. } elseif ($timeout < 0) {
  1007. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  1008. }
  1009. return $timeout;
  1010. }
  1011. /**
  1012. * Reads pipes, executes callback.
  1013. *
  1014. * @param bool $blocking Whether to use blocking calls or not.
  1015. * @param bool $close Whether to close file handles or not.
  1016. */
  1017. private function readPipes($blocking, $close)
  1018. {
  1019. if ($close) {
  1020. $result = $this->processPipes->readAndCloseHandles($blocking);
  1021. } else {
  1022. $result = $this->processPipes->read($blocking);
  1023. }
  1024. foreach ($result as $type => $data) {
  1025. if (3 == $type) {
  1026. $this->fallbackExitcode = (int) $data;
  1027. } else {
  1028. call_user_func($this->callback, $type === self::STDOUT ? self::OUT : self::ERR, $data);
  1029. }
  1030. }
  1031. }
  1032. /**
  1033. * Captures the exitcode if mentioned in the process information.
  1034. */
  1035. private function captureExitCode()
  1036. {
  1037. if (isset($this->processInformation['exitcode']) && -1 != $this->processInformation['exitcode']) {
  1038. $this->exitcode = $this->processInformation['exitcode'];
  1039. }
  1040. }
  1041. /**
  1042. * Closes process resource, closes file handles, sets the exitcode.
  1043. *
  1044. * @return int The exitcode
  1045. */
  1046. private function close()
  1047. {
  1048. $this->processPipes->close();
  1049. if (is_resource($this->process)) {
  1050. $exitcode = proc_close($this->process);
  1051. } else {
  1052. $exitcode = -1;
  1053. }
  1054. $this->exitcode = -1 !== $exitcode ? $exitcode : (null !== $this->exitcode ? $this->exitcode : -1);
  1055. $this->status = self::STATUS_TERMINATED;
  1056. if (-1 === $this->exitcode && null !== $this->fallbackExitcode) {
  1057. $this->exitcode = $this->fallbackExitcode;
  1058. } elseif (-1 === $this->exitcode && $this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
  1059. // if process has been signaled, no exitcode but a valid termsig, apply Unix convention
  1060. $this->exitcode = 128 + $this->processInformation['termsig'];
  1061. }
  1062. return $this->exitcode;
  1063. }
  1064. /**
  1065. * Resets data related to the latest run of the process.
  1066. */
  1067. private function resetProcessData()
  1068. {
  1069. $this->starttime = null;
  1070. $this->callback = null;
  1071. $this->exitcode = null;
  1072. $this->fallbackExitcode = null;
  1073. $this->processInformation = null;
  1074. $this->stdout = null;
  1075. $this->stderr = null;
  1076. $this->process = null;
  1077. $this->status = self::STATUS_READY;
  1078. $this->incrementalOutputOffset = 0;
  1079. $this->incrementalErrorOutputOffset = 0;
  1080. }
  1081. /**
  1082. * Sends a POSIX signal to the process.
  1083. *
  1084. * @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
  1085. * @param bool $throwException Whether to throw exception in case signal failed
  1086. *
  1087. * @return bool True if the signal was sent successfully, false otherwise
  1088. *
  1089. * @throws LogicException In case the process is not running
  1090. * @throws RuntimeException In case --enable-sigchild is activated
  1091. * @throws RuntimeException In case of failure
  1092. */
  1093. private function doSignal($signal, $throwException)
  1094. {
  1095. if (!$this->isRunning()) {
  1096. if ($throwException) {
  1097. throw new LogicException('Can not send signal on a non running process.');
  1098. }
  1099. return false;
  1100. }
  1101. if ($this->isSigchildEnabled()) {
  1102. if ($throwException) {
  1103. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. The process can not be signaled.');
  1104. }
  1105. return false;
  1106. }
  1107. if (true !== @proc_terminate($this->process, $signal)) {
  1108. if ($throwException) {
  1109. throw new RuntimeException(sprintf('Error while sending signal `%s`.', $signal));
  1110. }
  1111. return false;
  1112. }
  1113. return true;
  1114. }
  1115. /**
  1116. * Ensures the process is running or terminated, throws a LogicException if the process has a not started.
  1117. *
  1118. * @param string $functionName The function name that was called.
  1119. *
  1120. * @throws LogicException If the process has not run.
  1121. */
  1122. private function requireProcessIsStarted($functionName)
  1123. {
  1124. if (!$this->isStarted()) {
  1125. throw new LogicException(sprintf('Process must be started before calling %s.', $functionName));
  1126. }
  1127. }
  1128. /**
  1129. * Ensures the process is terminated, throws a LogicException if the process has a status different than `terminated`.
  1130. *
  1131. * @param string $functionName The function name that was called.
  1132. *
  1133. * @throws LogicException If the process is not yet terminated.
  1134. */
  1135. private function requireProcessIsTerminated($functionName)
  1136. {
  1137. if (!$this->isTerminated()) {
  1138. throw new LogicException(sprintf('Process must be terminated before calling %s.', $functionName));
  1139. }
  1140. }
  1141. }