菜谱项目

Process.php 55KB

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