Process.php 55 KB

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