Process.php 50 KB

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