Process.php 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: yunwuxin <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. use think\process\exception\Failed as ProcessFailedException;
  13. use think\process\exception\Timeout as ProcessTimeoutException;
  14. use think\process\pipes\Pipes;
  15. use think\process\pipes\Unix as UnixPipes;
  16. use think\process\pipes\Windows as WindowsPipes;
  17. use think\process\Utils;
  18. class Process
  19. {
  20. const ERR = 'err';
  21. const OUT = 'out';
  22. const STATUS_READY = 'ready';
  23. const STATUS_STARTED = 'started';
  24. const STATUS_TERMINATED = 'terminated';
  25. const STDIN = 0;
  26. const STDOUT = 1;
  27. const STDERR = 2;
  28. const TIMEOUT_PRECISION = 0.2;
  29. private $callback;
  30. private $commandline;
  31. private $cwd;
  32. private $env;
  33. private $input;
  34. private $starttime;
  35. private $lastOutputTime;
  36. private $timeout;
  37. private $idleTimeout;
  38. private $options;
  39. private $exitcode;
  40. private $fallbackExitcode;
  41. private $processInformation;
  42. private $outputDisabled = false;
  43. private $stdout;
  44. private $stderr;
  45. private $enhanceWindowsCompatibility = true;
  46. private $enhanceSigchildCompatibility;
  47. private $process;
  48. private $status = self::STATUS_READY;
  49. private $incrementalOutputOffset = 0;
  50. private $incrementalErrorOutputOffset = 0;
  51. private $tty;
  52. private $pty;
  53. private $useFileHandles = false;
  54. /** @var Pipes */
  55. private $processPipes;
  56. private $latestSignal;
  57. private static $sigchild;
  58. /**
  59. * @var array
  60. */
  61. public static $exitCodes = [
  62. 0 => 'OK',
  63. 1 => 'General error',
  64. 2 => 'Misuse of shell builtins',
  65. 126 => 'Invoked command cannot execute',
  66. 127 => 'Command not found',
  67. 128 => 'Invalid exit argument',
  68. // signals
  69. 129 => 'Hangup',
  70. 130 => 'Interrupt',
  71. 131 => 'Quit and dump core',
  72. 132 => 'Illegal instruction',
  73. 133 => 'Trace/breakpoint trap',
  74. 134 => 'Process aborted',
  75. 135 => 'Bus error: "access to undefined portion of memory object"',
  76. 136 => 'Floating point exception: "erroneous arithmetic operation"',
  77. 137 => 'Kill (terminate immediately)',
  78. 138 => 'User-defined 1',
  79. 139 => 'Segmentation violation',
  80. 140 => 'User-defined 2',
  81. 141 => 'Write to pipe with no one reading',
  82. 142 => 'Signal raised by alarm',
  83. 143 => 'Termination (request to terminate)',
  84. // 144 - not defined
  85. 145 => 'Child process terminated, stopped (or continued*)',
  86. 146 => 'Continue if stopped',
  87. 147 => 'Stop executing temporarily',
  88. 148 => 'Terminal stop signal',
  89. 149 => 'Background process attempting to read from tty ("in")',
  90. 150 => 'Background process attempting to write to tty ("out")',
  91. 151 => 'Urgent data available on socket',
  92. 152 => 'CPU time limit exceeded',
  93. 153 => 'File size limit exceeded',
  94. 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
  95. 155 => 'Profiling timer expired',
  96. // 156 - not defined
  97. 157 => 'Pollable event',
  98. // 158 - not defined
  99. 159 => 'Bad syscall',
  100. ];
  101. /**
  102. * 构造方法
  103. * @access public
  104. * @param string $commandline 指令
  105. * @param string|null $cwd 工作目录
  106. * @param array|null $env 环境变量
  107. * @param string|null $input 输入
  108. * @param int|float|null $timeout 超时时间
  109. * @param array $options proc_open的选项
  110. * @throws \RuntimeException
  111. * @api
  112. */
  113. public function __construct($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = [])
  114. {
  115. if (!function_exists('proc_open')) {
  116. throw new \RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
  117. }
  118. $this->commandline = $commandline;
  119. $this->cwd = $cwd;
  120. if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || '\\' === DIRECTORY_SEPARATOR)) {
  121. $this->cwd = getcwd();
  122. }
  123. if (null !== $env) {
  124. $this->setEnv($env);
  125. }
  126. $this->input = $input;
  127. $this->setTimeout($timeout);
  128. $this->useFileHandles = '\\' === DIRECTORY_SEPARATOR;
  129. $this->pty = false;
  130. $this->enhanceWindowsCompatibility = true;
  131. $this->enhanceSigchildCompatibility = '\\' !== DIRECTORY_SEPARATOR && $this->isSigchildEnabled();
  132. $this->options = array_replace([
  133. 'suppress_errors' => true,
  134. 'binary_pipes' => true,
  135. ], $options);
  136. }
  137. public function __destruct()
  138. {
  139. $this->stop();
  140. }
  141. public function __clone()
  142. {
  143. $this->resetProcessData();
  144. }
  145. /**
  146. * 运行指令
  147. * @access public
  148. * @param callback|null $callback
  149. * @return int
  150. */
  151. public function run($callback = null)
  152. {
  153. $this->start($callback);
  154. return $this->wait();
  155. }
  156. /**
  157. * 运行指令
  158. * @access public
  159. * @param callable|null $callback
  160. * @return self
  161. * @throws \RuntimeException
  162. * @throws ProcessFailedException
  163. */
  164. public function mustRun($callback = null)
  165. {
  166. if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
  167. throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
  168. }
  169. if (0 !== $this->run($callback)) {
  170. throw new ProcessFailedException($this);
  171. }
  172. return $this;
  173. }
  174. /**
  175. * 启动进程并写到 STDIN 输入后返回。
  176. * @access public
  177. * @param callable|null $callback
  178. * @throws \RuntimeException
  179. * @throws \RuntimeException
  180. * @throws \LogicException
  181. */
  182. public function start($callback = null)
  183. {
  184. if ($this->isRunning()) {
  185. throw new \RuntimeException('Process is already running');
  186. }
  187. if ($this->outputDisabled && null !== $callback) {
  188. throw new \LogicException('Output has been disabled, enable it to allow the use of a callback.');
  189. }
  190. $this->resetProcessData();
  191. $this->starttime = $this->lastOutputTime = microtime(true);
  192. $this->callback = $this->buildCallback($callback);
  193. $descriptors = $this->getDescriptors();
  194. $commandline = $this->commandline;
  195. if ('\\' === DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) {
  196. $commandline = 'cmd /V:ON /E:ON /C "(' . $commandline . ')';
  197. foreach ($this->processPipes->getFiles() as $offset => $filename) {
  198. $commandline .= ' ' . $offset . '>' . Utils::escapeArgument($filename);
  199. }
  200. $commandline .= '"';
  201. if (!isset($this->options['bypass_shell'])) {
  202. $this->options['bypass_shell'] = true;
  203. }
  204. }
  205. $this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $this->env, $this->options);
  206. if (!is_resource($this->process)) {
  207. throw new \RuntimeException('Unable to launch a new process.');
  208. }
  209. $this->status = self::STATUS_STARTED;
  210. if ($this->tty) {
  211. return;
  212. }
  213. $this->updateStatus(false);
  214. $this->checkTimeout();
  215. }
  216. /**
  217. * 重启进程
  218. * @access public
  219. * @param callable|null $callback
  220. * @return Process
  221. * @throws \RuntimeException
  222. * @throws \RuntimeException
  223. */
  224. public function restart($callback = null)
  225. {
  226. if ($this->isRunning()) {
  227. throw new \RuntimeException('Process is already running');
  228. }
  229. $process = clone $this;
  230. $process->start($callback);
  231. return $process;
  232. }
  233. /**
  234. * 等待要终止的进程
  235. * @access public
  236. * @param callable|null $callback
  237. * @return int
  238. */
  239. public function wait($callback = null)
  240. {
  241. $this->requireProcessIsStarted(__FUNCTION__);
  242. $this->updateStatus(false);
  243. if (null !== $callback) {
  244. $this->callback = $this->buildCallback($callback);
  245. }
  246. do {
  247. $this->checkTimeout();
  248. $running = '\\' === DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
  249. $close = '\\' !== DIRECTORY_SEPARATOR || !$running;
  250. $this->readPipes(true, $close);
  251. } while ($running);
  252. while ($this->isRunning()) {
  253. usleep(1000);
  254. }
  255. if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {
  256. throw new \RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig']));
  257. }
  258. return $this->exitcode;
  259. }
  260. /**
  261. * 获取PID
  262. * @access public
  263. * @return int|null
  264. * @throws \RuntimeException
  265. */
  266. public function getPid()
  267. {
  268. if ($this->isSigchildEnabled()) {
  269. throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved.');
  270. }
  271. $this->updateStatus(false);
  272. return $this->isRunning() ? $this->processInformation['pid'] : null;
  273. }
  274. /**
  275. * 将一个 POSIX 信号发送到进程中
  276. * @access public
  277. * @param int $signal
  278. * @return Process
  279. */
  280. public function signal($signal)
  281. {
  282. $this->doSignal($signal, true);
  283. return $this;
  284. }
  285. /**
  286. * 禁用从底层过程获取输出和错误输出。
  287. * @access public
  288. * @return Process
  289. */
  290. public function disableOutput()
  291. {
  292. if ($this->isRunning()) {
  293. throw new \RuntimeException('Disabling output while the process is running is not possible.');
  294. }
  295. if (null !== $this->idleTimeout) {
  296. throw new \LogicException('Output can not be disabled while an idle timeout is set.');
  297. }
  298. $this->outputDisabled = true;
  299. return $this;
  300. }
  301. /**
  302. * 开启从底层过程获取输出和错误输出。
  303. * @access public
  304. * @return Process
  305. * @throws \RuntimeException
  306. */
  307. public function enableOutput()
  308. {
  309. if ($this->isRunning()) {
  310. throw new \RuntimeException('Enabling output while the process is running is not possible.');
  311. }
  312. $this->outputDisabled = false;
  313. return $this;
  314. }
  315. /**
  316. * 输出是否禁用
  317. * @access public
  318. * @return bool
  319. */
  320. public function isOutputDisabled()
  321. {
  322. return $this->outputDisabled;
  323. }
  324. /**
  325. * 获取当前的输出管道
  326. * @access public
  327. * @return string
  328. * @throws \LogicException
  329. * @api
  330. */
  331. public function getOutput()
  332. {
  333. if ($this->outputDisabled) {
  334. throw new \LogicException('Output has been disabled.');
  335. }
  336. $this->requireProcessIsStarted(__FUNCTION__);
  337. $this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  338. return $this->stdout;
  339. }
  340. /**
  341. * 以增量方式返回的输出结果。
  342. * @access public
  343. * @return string
  344. */
  345. public function getIncrementalOutput()
  346. {
  347. $this->requireProcessIsStarted(__FUNCTION__);
  348. $data = $this->getOutput();
  349. $latest = substr($data, $this->incrementalOutputOffset);
  350. if (false === $latest) {
  351. return '';
  352. }
  353. $this->incrementalOutputOffset = strlen($data);
  354. return $latest;
  355. }
  356. /**
  357. * 清空输出
  358. * @access public
  359. * @return Process
  360. */
  361. public function clearOutput()
  362. {
  363. $this->stdout = '';
  364. $this->incrementalOutputOffset = 0;
  365. return $this;
  366. }
  367. /**
  368. * 返回当前的错误输出的过程 (STDERR)。
  369. * @access public
  370. * @return string
  371. */
  372. public function getErrorOutput()
  373. {
  374. if ($this->outputDisabled) {
  375. throw new \LogicException('Output has been disabled.');
  376. }
  377. $this->requireProcessIsStarted(__FUNCTION__);
  378. $this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  379. return $this->stderr;
  380. }
  381. /**
  382. * 以增量方式返回 errorOutput
  383. * @access public
  384. * @return string
  385. */
  386. public function getIncrementalErrorOutput()
  387. {
  388. $this->requireProcessIsStarted(__FUNCTION__);
  389. $data = $this->getErrorOutput();
  390. $latest = substr($data, $this->incrementalErrorOutputOffset);
  391. if (false === $latest) {
  392. return '';
  393. }
  394. $this->incrementalErrorOutputOffset = strlen($data);
  395. return $latest;
  396. }
  397. /**
  398. * 清空 errorOutput
  399. * @access public
  400. * @return Process
  401. */
  402. public function clearErrorOutput()
  403. {
  404. $this->stderr = '';
  405. $this->incrementalErrorOutputOffset = 0;
  406. return $this;
  407. }
  408. /**
  409. * 获取退出码
  410. * @access public
  411. * @return null|int
  412. */
  413. public function getExitCode()
  414. {
  415. if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
  416. throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
  417. }
  418. $this->updateStatus(false);
  419. return $this->exitcode;
  420. }
  421. /**
  422. * 获取退出文本
  423. * @access public
  424. * @return null|string
  425. */
  426. public function getExitCodeText()
  427. {
  428. if (null === $exitcode = $this->getExitCode()) {
  429. return;
  430. }
  431. return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
  432. }
  433. /**
  434. * 检查是否成功
  435. * @access public
  436. * @return bool
  437. */
  438. public function isSuccessful()
  439. {
  440. return 0 === $this->getExitCode();
  441. }
  442. /**
  443. * 是否未捕获的信号已被终止子进程
  444. * @access public
  445. * @return bool
  446. */
  447. public function hasBeenSignaled()
  448. {
  449. $this->requireProcessIsTerminated(__FUNCTION__);
  450. if ($this->isSigchildEnabled()) {
  451. throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  452. }
  453. $this->updateStatus(false);
  454. return $this->processInformation['signaled'];
  455. }
  456. /**
  457. * 返回导致子进程终止其执行的数。
  458. * @access public
  459. * @return int
  460. */
  461. public function getTermSignal()
  462. {
  463. $this->requireProcessIsTerminated(__FUNCTION__);
  464. if ($this->isSigchildEnabled()) {
  465. throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  466. }
  467. $this->updateStatus(false);
  468. return $this->processInformation['termsig'];
  469. }
  470. /**
  471. * 检查子进程信号是否已停止
  472. * @access public
  473. * @return bool
  474. */
  475. public function hasBeenStopped()
  476. {
  477. $this->requireProcessIsTerminated(__FUNCTION__);
  478. $this->updateStatus(false);
  479. return $this->processInformation['stopped'];
  480. }
  481. /**
  482. * 返回导致子进程停止其执行的数。
  483. * @access public
  484. * @return int
  485. */
  486. public function getStopSignal()
  487. {
  488. $this->requireProcessIsTerminated(__FUNCTION__);
  489. $this->updateStatus(false);
  490. return $this->processInformation['stopsig'];
  491. }
  492. /**
  493. * 检查是否正在运行
  494. * @access public
  495. * @return bool
  496. */
  497. public function isRunning()
  498. {
  499. if (self::STATUS_STARTED !== $this->status) {
  500. return false;
  501. }
  502. $this->updateStatus(false);
  503. return $this->processInformation['running'];
  504. }
  505. /**
  506. * 检查是否已开始
  507. * @access public
  508. * @return bool
  509. */
  510. public function isStarted()
  511. {
  512. return self::STATUS_READY != $this->status;
  513. }
  514. /**
  515. * 检查是否已终止
  516. * @access public
  517. * @return bool
  518. */
  519. public function isTerminated()
  520. {
  521. $this->updateStatus(false);
  522. return self::STATUS_TERMINATED == $this->status;
  523. }
  524. /**
  525. * 获取当前的状态
  526. * @access public
  527. * @return string
  528. */
  529. public function getStatus()
  530. {
  531. $this->updateStatus(false);
  532. return $this->status;
  533. }
  534. /**
  535. * 终止进程
  536. * @access public
  537. */
  538. public function stop()
  539. {
  540. if ($this->isRunning()) {
  541. if ('\\' === DIRECTORY_SEPARATOR && !$this->isSigchildEnabled()) {
  542. exec(sprintf('taskkill /F /T /PID %d 2>&1', $this->getPid()), $output, $exitCode);
  543. if ($exitCode > 0) {
  544. throw new \RuntimeException('Unable to kill the process');
  545. }
  546. } else {
  547. $pids = preg_split('/\s+/', `ps -o pid --no-heading --ppid {$this->getPid()}`);
  548. foreach ($pids as $pid) {
  549. if (is_numeric($pid)) {
  550. posix_kill($pid, 9);
  551. }
  552. }
  553. }
  554. }
  555. $this->updateStatus(false);
  556. if ($this->processInformation['running']) {
  557. $this->close();
  558. }
  559. return $this->exitcode;
  560. }
  561. /**
  562. * 添加一行输出
  563. * @access public
  564. * @param string $line
  565. */
  566. public function addOutput($line)
  567. {
  568. $this->lastOutputTime = microtime(true);
  569. $this->stdout .= $line;
  570. }
  571. /**
  572. * 添加一行错误输出
  573. * @access public
  574. * @param string $line
  575. */
  576. public function addErrorOutput($line)
  577. {
  578. $this->lastOutputTime = microtime(true);
  579. $this->stderr .= $line;
  580. }
  581. /**
  582. * 获取被执行的指令
  583. * @access public
  584. * @return string
  585. */
  586. public function getCommandLine()
  587. {
  588. return $this->commandline;
  589. }
  590. /**
  591. * 设置指令
  592. * @access public
  593. * @param string $commandline
  594. * @return self
  595. */
  596. public function setCommandLine($commandline)
  597. {
  598. $this->commandline = $commandline;
  599. return $this;
  600. }
  601. /**
  602. * 获取超时时间
  603. * @access public
  604. * @return float|null
  605. */
  606. public function getTimeout()
  607. {
  608. return $this->timeout;
  609. }
  610. /**
  611. * 获取idle超时时间
  612. * @access public
  613. * @return float|null
  614. */
  615. public function getIdleTimeout()
  616. {
  617. return $this->idleTimeout;
  618. }
  619. /**
  620. * 设置超时时间
  621. * @access public
  622. * @param int|float|null $timeout
  623. * @return self
  624. */
  625. public function setTimeout($timeout)
  626. {
  627. $this->timeout = $this->validateTimeout($timeout);
  628. return $this;
  629. }
  630. /**
  631. * 设置idle超时时间
  632. * @access public
  633. * @param int|float|null $timeout
  634. * @return self
  635. */
  636. public function setIdleTimeout($timeout)
  637. {
  638. if (null !== $timeout && $this->outputDisabled) {
  639. throw new \LogicException('Idle timeout can not be set while the output is disabled.');
  640. }
  641. $this->idleTimeout = $this->validateTimeout($timeout);
  642. return $this;
  643. }
  644. /**
  645. * 设置TTY
  646. * @access public
  647. * @param bool $tty
  648. * @return self
  649. */
  650. public function setTty($tty)
  651. {
  652. if ('\\' === DIRECTORY_SEPARATOR && $tty) {
  653. throw new \RuntimeException('TTY mode is not supported on Windows platform.');
  654. }
  655. if ($tty && (!file_exists('/dev/tty') || !is_readable('/dev/tty'))) {
  656. throw new \RuntimeException('TTY mode requires /dev/tty to be readable.');
  657. }
  658. $this->tty = (bool) $tty;
  659. return $this;
  660. }
  661. /**
  662. * 检查是否是tty模式
  663. * @access public
  664. * @return bool
  665. */
  666. public function isTty()
  667. {
  668. return $this->tty;
  669. }
  670. /**
  671. * 设置pty模式
  672. * @access public
  673. * @param bool $bool
  674. * @return self
  675. */
  676. public function setPty($bool)
  677. {
  678. $this->pty = (bool) $bool;
  679. return $this;
  680. }
  681. /**
  682. * 是否是pty模式
  683. * @access public
  684. * @return bool
  685. */
  686. public function isPty()
  687. {
  688. return $this->pty;
  689. }
  690. /**
  691. * 获取工作目录
  692. * @access public
  693. * @return string|null
  694. */
  695. public function getWorkingDirectory()
  696. {
  697. if (null === $this->cwd) {
  698. return getcwd() ?: null;
  699. }
  700. return $this->cwd;
  701. }
  702. /**
  703. * 设置工作目录
  704. * @access public
  705. * @param string $cwd
  706. * @return self
  707. */
  708. public function setWorkingDirectory($cwd)
  709. {
  710. $this->cwd = $cwd;
  711. return $this;
  712. }
  713. /**
  714. * 获取环境变量
  715. * @access public
  716. * @return array
  717. */
  718. public function getEnv()
  719. {
  720. return $this->env;
  721. }
  722. /**
  723. * 设置环境变量
  724. * @access public
  725. * @param array $env
  726. * @return self
  727. */
  728. public function setEnv(array $env)
  729. {
  730. $env = array_filter($env, function ($value) {
  731. return !is_array($value);
  732. });
  733. $this->env = [];
  734. foreach ($env as $key => $value) {
  735. $this->env[(binary) $key] = (binary) $value;
  736. }
  737. return $this;
  738. }
  739. /**
  740. * 获取输入
  741. * @access public
  742. * @return null|string
  743. */
  744. public function getInput()
  745. {
  746. return $this->input;
  747. }
  748. /**
  749. * 设置输入
  750. * @access public
  751. * @param mixed $input
  752. * @return self
  753. */
  754. public function setInput($input)
  755. {
  756. if ($this->isRunning()) {
  757. throw new \LogicException('Input can not be set while the process is running.');
  758. }
  759. $this->input = Utils::validateInput(sprintf('%s::%s', __CLASS__, __FUNCTION__), $input);
  760. return $this;
  761. }
  762. /**
  763. * 获取proc_open的选项
  764. * @access public
  765. * @return array
  766. */
  767. public function getOptions()
  768. {
  769. return $this->options;
  770. }
  771. /**
  772. * 设置proc_open的选项
  773. * @access public
  774. * @param array $options
  775. * @return self
  776. */
  777. public function setOptions(array $options)
  778. {
  779. $this->options = $options;
  780. return $this;
  781. }
  782. /**
  783. * 是否兼容windows
  784. * @access public
  785. * @return bool
  786. */
  787. public function getEnhanceWindowsCompatibility()
  788. {
  789. return $this->enhanceWindowsCompatibility;
  790. }
  791. /**
  792. * 设置是否兼容windows
  793. * @access public
  794. * @param bool $enhance
  795. * @return self
  796. */
  797. public function setEnhanceWindowsCompatibility($enhance)
  798. {
  799. $this->enhanceWindowsCompatibility = (bool) $enhance;
  800. return $this;
  801. }
  802. /**
  803. * 返回是否 sigchild 兼容模式激活
  804. * @access public
  805. * @return bool
  806. */
  807. public function getEnhanceSigchildCompatibility()
  808. {
  809. return $this->enhanceSigchildCompatibility;
  810. }
  811. /**
  812. * 激活 sigchild 兼容性模式。
  813. * @access public
  814. * @param bool $enhance
  815. * @return self
  816. */
  817. public function setEnhanceSigchildCompatibility($enhance)
  818. {
  819. $this->enhanceSigchildCompatibility = (bool) $enhance;
  820. return $this;
  821. }
  822. /**
  823. * 是否超时
  824. */
  825. public function checkTimeout()
  826. {
  827. if (self::STATUS_STARTED !== $this->status) {
  828. return;
  829. }
  830. if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
  831. $this->stop();
  832. throw new ProcessTimeoutException($this, ProcessTimeoutException::TYPE_GENERAL);
  833. }
  834. if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
  835. $this->stop();
  836. throw new ProcessTimeoutException($this, ProcessTimeoutException::TYPE_IDLE);
  837. }
  838. }
  839. /**
  840. * 是否支持pty
  841. * @access public
  842. * @return bool
  843. */
  844. public static function isPtySupported()
  845. {
  846. static $result;
  847. if (null !== $result) {
  848. return $result;
  849. }
  850. if ('\\' === DIRECTORY_SEPARATOR) {
  851. return $result = false;
  852. }
  853. $proc = @proc_open('echo 1', [['pty'], ['pty'], ['pty']], $pipes);
  854. if (is_resource($proc)) {
  855. proc_close($proc);
  856. return $result = true;
  857. }
  858. return $result = false;
  859. }
  860. /**
  861. * 创建所需的 proc_open 的描述符
  862. * @access private
  863. * @return array
  864. */
  865. private function getDescriptors()
  866. {
  867. if ('\\' === DIRECTORY_SEPARATOR) {
  868. $this->processPipes = WindowsPipes::create($this, $this->input);
  869. } else {
  870. $this->processPipes = UnixPipes::create($this, $this->input);
  871. }
  872. $descriptors = $this->processPipes->getDescriptors($this->outputDisabled);
  873. if (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  874. $descriptors = array_merge($descriptors, [['pipe', 'w']]);
  875. $this->commandline = '(' . $this->commandline . ') 3>/dev/null; code=$?; echo $code >&3; exit $code';
  876. }
  877. return $descriptors;
  878. }
  879. /**
  880. * 建立 wait () 使用的回调。
  881. * @access protected
  882. * @param callable|null $callback
  883. * @return callable
  884. */
  885. protected function buildCallback($callback)
  886. {
  887. $out = self::OUT;
  888. $callback = function ($type, $data) use ($callback, $out) {
  889. if ($out == $type) {
  890. $this->addOutput($data);
  891. } else {
  892. $this->addErrorOutput($data);
  893. }
  894. if (null !== $callback) {
  895. call_user_func($callback, $type, $data);
  896. }
  897. };
  898. return $callback;
  899. }
  900. /**
  901. * 更新状态
  902. * @access protected
  903. * @param bool $blocking
  904. */
  905. protected function updateStatus($blocking)
  906. {
  907. if (self::STATUS_STARTED !== $this->status) {
  908. return;
  909. }
  910. $this->processInformation = proc_get_status($this->process);
  911. $this->captureExitCode();
  912. $this->readPipes($blocking, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  913. if (!$this->processInformation['running']) {
  914. $this->close();
  915. }
  916. }
  917. /**
  918. * 是否开启 '--enable-sigchild'
  919. * @access protected
  920. * @return bool
  921. */
  922. protected function isSigchildEnabled()
  923. {
  924. if (null !== self::$sigchild) {
  925. return self::$sigchild;
  926. }
  927. if (!function_exists('phpinfo')) {
  928. return self::$sigchild = false;
  929. }
  930. ob_start();
  931. phpinfo(INFO_GENERAL);
  932. return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  933. }
  934. /**
  935. * 验证是否超时
  936. * @access private
  937. * @param int|float|null $timeout
  938. * @return float|null
  939. */
  940. private function validateTimeout($timeout)
  941. {
  942. $timeout = (float) $timeout;
  943. if (0.0 === $timeout) {
  944. $timeout = null;
  945. } elseif ($timeout < 0) {
  946. throw new \InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  947. }
  948. return $timeout;
  949. }
  950. /**
  951. * 读取pipes
  952. * @access private
  953. * @param bool $blocking
  954. * @param bool $close
  955. */
  956. private function readPipes($blocking, $close)
  957. {
  958. $result = $this->processPipes->readAndWrite($blocking, $close);
  959. $callback = $this->callback;
  960. foreach ($result as $type => $data) {
  961. if (3 == $type) {
  962. $this->fallbackExitcode = (int) $data;
  963. } else {
  964. $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data);
  965. }
  966. }
  967. }
  968. /**
  969. * 捕获退出码
  970. */
  971. private function captureExitCode()
  972. {
  973. if (isset($this->processInformation['exitcode']) && -1 != $this->processInformation['exitcode']) {
  974. $this->exitcode = $this->processInformation['exitcode'];
  975. }
  976. }
  977. /**
  978. * 关闭资源
  979. * @access private
  980. * @return int 退出码
  981. */
  982. private function close()
  983. {
  984. $this->processPipes->close();
  985. if (is_resource($this->process)) {
  986. $exitcode = proc_close($this->process);
  987. } else {
  988. $exitcode = -1;
  989. }
  990. $this->exitcode = -1 !== $exitcode ? $exitcode : (null !== $this->exitcode ? $this->exitcode : -1);
  991. $this->status = self::STATUS_TERMINATED;
  992. if (-1 === $this->exitcode && null !== $this->fallbackExitcode) {
  993. $this->exitcode = $this->fallbackExitcode;
  994. } elseif (-1 === $this->exitcode && $this->processInformation['signaled']
  995. && 0 < $this->processInformation['termsig']
  996. ) {
  997. $this->exitcode = 128 + $this->processInformation['termsig'];
  998. }
  999. return $this->exitcode;
  1000. }
  1001. /**
  1002. * 重置数据
  1003. */
  1004. private function resetProcessData()
  1005. {
  1006. $this->starttime = null;
  1007. $this->callback = null;
  1008. $this->exitcode = null;
  1009. $this->fallbackExitcode = null;
  1010. $this->processInformation = null;
  1011. $this->stdout = null;
  1012. $this->stderr = null;
  1013. $this->process = null;
  1014. $this->latestSignal = null;
  1015. $this->status = self::STATUS_READY;
  1016. $this->incrementalOutputOffset = 0;
  1017. $this->incrementalErrorOutputOffset = 0;
  1018. }
  1019. /**
  1020. * 将一个 POSIX 信号发送到进程中。
  1021. * @access private
  1022. * @param int $signal
  1023. * @param bool $throwException
  1024. * @return bool
  1025. */
  1026. private function doSignal($signal, $throwException)
  1027. {
  1028. if (!$this->isRunning()) {
  1029. if ($throwException) {
  1030. throw new \LogicException('Can not send signal on a non running process.');
  1031. }
  1032. return false;
  1033. }
  1034. if ($this->isSigchildEnabled()) {
  1035. if ($throwException) {
  1036. throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. The process can not be signaled.');
  1037. }
  1038. return false;
  1039. }
  1040. if (true !== @proc_terminate($this->process, $signal)) {
  1041. if ($throwException) {
  1042. throw new \RuntimeException(sprintf('Error while sending signal `%s`.', $signal));
  1043. }
  1044. return false;
  1045. }
  1046. $this->latestSignal = $signal;
  1047. return true;
  1048. }
  1049. /**
  1050. * 确保进程已经开启
  1051. * @access private
  1052. * @param string $functionName
  1053. */
  1054. private function requireProcessIsStarted($functionName)
  1055. {
  1056. if (!$this->isStarted()) {
  1057. throw new \LogicException(sprintf('Process must be started before calling %s.', $functionName));
  1058. }
  1059. }
  1060. /**
  1061. * 确保进程已经终止
  1062. * @access private
  1063. * @param string $functionName
  1064. */
  1065. private function requireProcessIsTerminated($functionName)
  1066. {
  1067. if (!$this->isTerminated()) {
  1068. throw new \LogicException(sprintf('Process must be terminated before calling %s.', $functionName));
  1069. }
  1070. }
  1071. }