| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268 | 
							- <?php
 
- // +----------------------------------------------------------------------
 
- // | ThinkPHP [ WE CAN DO IT JUST THINK ]
 
- // +----------------------------------------------------------------------
 
- // | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
 
- // +----------------------------------------------------------------------
 
- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
 
- // +----------------------------------------------------------------------
 
- // | Author: yunwuxin <448901948@qq.com>
 
- // +----------------------------------------------------------------------
 
- namespace think;
 
- use think\process\exception\Failed as ProcessFailedException;
 
- use think\process\exception\Timeout as ProcessTimeoutException;
 
- use think\process\pipes\Pipes;
 
- use think\process\pipes\Unix as UnixPipes;
 
- use think\process\pipes\Windows as WindowsPipes;
 
- use think\process\Utils;
 
- class Process
 
- {
 
-     const ERR = 'err';
 
-     const OUT = 'out';
 
-     const STATUS_READY      = 'ready';
 
-     const STATUS_STARTED    = 'started';
 
-     const STATUS_TERMINATED = 'terminated';
 
-     const STDIN  = 0;
 
-     const STDOUT = 1;
 
-     const STDERR = 2;
 
-     const TIMEOUT_PRECISION = 0.2;
 
-     private $callback;
 
-     private $commandline;
 
-     private $cwd;
 
-     private $env;
 
-     private $input;
 
-     private $starttime;
 
-     private $lastOutputTime;
 
-     private $timeout;
 
-     private $idleTimeout;
 
-     private $options;
 
-     private $exitcode;
 
-     private $fallbackExitcode;
 
-     private $processInformation;
 
-     private $outputDisabled = false;
 
-     private $stdout;
 
-     private $stderr;
 
-     private $enhanceWindowsCompatibility = true;
 
-     private $enhanceSigchildCompatibility;
 
-     private $process;
 
-     private $status                       = self::STATUS_READY;
 
-     private $incrementalOutputOffset      = 0;
 
-     private $incrementalErrorOutputOffset = 0;
 
-     private $tty;
 
-     private $pty;
 
-     private $useFileHandles = false;
 
-     /** @var Pipes */
 
-     private $processPipes;
 
-     private $latestSignal;
 
-     private static $sigchild;
 
-     /**
 
-      * @var array
 
-      */
 
-     public static $exitCodes = [
 
-         0   => 'OK',
 
-         1   => 'General error',
 
-         2   => 'Misuse of shell builtins',
 
-         126 => 'Invoked command cannot execute',
 
-         127 => 'Command not found',
 
-         128 => 'Invalid exit argument',
 
-         // signals
 
-         129 => 'Hangup',
 
-         130 => 'Interrupt',
 
-         131 => 'Quit and dump core',
 
-         132 => 'Illegal instruction',
 
-         133 => 'Trace/breakpoint trap',
 
-         134 => 'Process aborted',
 
-         135 => 'Bus error: "access to undefined portion of memory object"',
 
-         136 => 'Floating point exception: "erroneous arithmetic operation"',
 
-         137 => 'Kill (terminate immediately)',
 
-         138 => 'User-defined 1',
 
-         139 => 'Segmentation violation',
 
-         140 => 'User-defined 2',
 
-         141 => 'Write to pipe with no one reading',
 
-         142 => 'Signal raised by alarm',
 
-         143 => 'Termination (request to terminate)',
 
-         // 144 - not defined
 
-         145 => 'Child process terminated, stopped (or continued*)',
 
-         146 => 'Continue if stopped',
 
-         147 => 'Stop executing temporarily',
 
-         148 => 'Terminal stop signal',
 
-         149 => 'Background process attempting to read from tty ("in")',
 
-         150 => 'Background process attempting to write to tty ("out")',
 
-         151 => 'Urgent data available on socket',
 
-         152 => 'CPU time limit exceeded',
 
-         153 => 'File size limit exceeded',
 
-         154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
 
-         155 => 'Profiling timer expired',
 
-         // 156 - not defined
 
-         157 => 'Pollable event',
 
-         // 158 - not defined
 
-         159 => 'Bad syscall',
 
-     ];
 
-     /**
 
-      * 构造方法
 
-      * @access public
 
-      * @param  string         $commandline 指令
 
-      * @param  string|null    $cwd         工作目录
 
-      * @param  array|null     $env         环境变量
 
-      * @param  string|null    $input       输入
 
-      * @param  int|float|null $timeout     超时时间
 
-      * @param  array          $options     proc_open的选项
 
-      * @throws \RuntimeException
 
-      * @api
 
-      */
 
-     public function __construct($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = [])
 
-     {
 
-         if (!function_exists('proc_open')) {
 
-             throw new \RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
 
-         }
 
-         $this->commandline = $commandline;
 
-         $this->cwd         = $cwd;
 
-         if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || '\\' === DIRECTORY_SEPARATOR)) {
 
-             $this->cwd = getcwd();
 
-         }
 
-         if (null !== $env) {
 
-             $this->setEnv($env);
 
-         }
 
-         $this->input = $input;
 
-         $this->setTimeout($timeout);
 
-         $this->useFileHandles               = '\\' === DIRECTORY_SEPARATOR;
 
-         $this->pty                          = false;
 
-         $this->enhanceWindowsCompatibility  = true;
 
-         $this->enhanceSigchildCompatibility = '\\' !== DIRECTORY_SEPARATOR && $this->isSigchildEnabled();
 
-         $this->options                      = array_replace([
 
-             'suppress_errors' => true,
 
-             'binary_pipes'    => true,
 
-         ], $options);
 
-     }
 
-     public function __destruct()
 
-     {
 
-         $this->stop();
 
-     }
 
-     public function __clone()
 
-     {
 
-         $this->resetProcessData();
 
-     }
 
-     /**
 
-      * 运行指令
 
-      * @access public
 
-      * @param  callback|null $callback
 
-      * @return int
 
-      */
 
-     public function run($callback = null)
 
-     {
 
-         $this->start($callback);
 
-         return $this->wait();
 
-     }
 
-     /**
 
-      * 运行指令
 
-      * @access public
 
-      * @param  callable|null $callback
 
-      * @return self
 
-      * @throws \RuntimeException
 
-      * @throws ProcessFailedException
 
-      */
 
-     public function mustRun($callback = null)
 
-     {
 
-         if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
 
-             throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
 
-         }
 
-         if (0 !== $this->run($callback)) {
 
-             throw new ProcessFailedException($this);
 
-         }
 
-         return $this;
 
-     }
 
-     /**
 
-      * 启动进程并写到 STDIN 输入后返回。
 
-      * @access public
 
-      * @param  callable|null $callback
 
-      * @throws \RuntimeException
 
-      * @throws \RuntimeException
 
-      * @throws \LogicException
 
-      */
 
-     public function start($callback = null)
 
-     {
 
-         if ($this->isRunning()) {
 
-             throw new \RuntimeException('Process is already running');
 
-         }
 
-         if ($this->outputDisabled && null !== $callback) {
 
-             throw new \LogicException('Output has been disabled, enable it to allow the use of a callback.');
 
-         }
 
-         $this->resetProcessData();
 
-         $this->starttime = $this->lastOutputTime = microtime(true);
 
-         $this->callback  = $this->buildCallback($callback);
 
-         $descriptors     = $this->getDescriptors();
 
-         $commandline = $this->commandline;
 
-         if ('\\' === DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) {
 
-             $commandline = 'cmd /V:ON /E:ON /C "(' . $commandline . ')';
 
-             foreach ($this->processPipes->getFiles() as $offset => $filename) {
 
-                 $commandline .= ' ' . $offset . '>' . Utils::escapeArgument($filename);
 
-             }
 
-             $commandline .= '"';
 
-             if (!isset($this->options['bypass_shell'])) {
 
-                 $this->options['bypass_shell'] = true;
 
-             }
 
-         }
 
-         $this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $this->env, $this->options);
 
-         if (!is_resource($this->process)) {
 
-             throw new \RuntimeException('Unable to launch a new process.');
 
-         }
 
-         $this->status = self::STATUS_STARTED;
 
-         if ($this->tty) {
 
-             return;
 
-         }
 
-         $this->updateStatus(false);
 
-         $this->checkTimeout();
 
-     }
 
-     /**
 
-      * 重启进程
 
-      * @access public
 
-      * @param  callable|null $callback
 
-      * @return Process
 
-      * @throws \RuntimeException
 
-      * @throws \RuntimeException
 
-      */
 
-     public function restart($callback = null)
 
-     {
 
-         if ($this->isRunning()) {
 
-             throw new \RuntimeException('Process is already running');
 
-         }
 
-         $process = clone $this;
 
-         $process->start($callback);
 
-         return $process;
 
-     }
 
-     /**
 
-      * 等待要终止的进程
 
-      * @access public
 
-      * @param  callable|null $callback
 
-      * @return int
 
-      */
 
-     public function wait($callback = null)
 
-     {
 
-         $this->requireProcessIsStarted(__FUNCTION__);
 
-         $this->updateStatus(false);
 
-         if (null !== $callback) {
 
-             $this->callback = $this->buildCallback($callback);
 
-         }
 
-         do {
 
-             $this->checkTimeout();
 
-             $running = '\\' === DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
 
-             $close   = '\\' !== DIRECTORY_SEPARATOR || !$running;
 
-             $this->readPipes(true, $close);
 
-         } while ($running);
 
-         while ($this->isRunning()) {
 
-             usleep(1000);
 
-         }
 
-         if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {
 
-             throw new \RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig']));
 
-         }
 
-         return $this->exitcode;
 
-     }
 
-     /**
 
-      * 获取PID
 
-      * @access public
 
-      * @return int|null
 
-      * @throws \RuntimeException
 
-      */
 
-     public function getPid()
 
-     {
 
-         if ($this->isSigchildEnabled()) {
 
-             throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved.');
 
-         }
 
-         $this->updateStatus(false);
 
-         return $this->isRunning() ? $this->processInformation['pid'] : null;
 
-     }
 
-     /**
 
-      * 将一个 POSIX 信号发送到进程中
 
-      * @access public
 
-      * @param  int $signal
 
-      * @return Process
 
-      */
 
-     public function signal($signal)
 
-     {
 
-         $this->doSignal($signal, true);
 
-         return $this;
 
-     }
 
-     /**
 
-      * 禁用从底层过程获取输出和错误输出。
 
-      * @access public
 
-      * @return Process
 
-      */
 
-     public function disableOutput()
 
-     {
 
-         if ($this->isRunning()) {
 
-             throw new \RuntimeException('Disabling output while the process is running is not possible.');
 
-         }
 
-         if (null !== $this->idleTimeout) {
 
-             throw new \LogicException('Output can not be disabled while an idle timeout is set.');
 
-         }
 
-         $this->outputDisabled = true;
 
-         return $this;
 
-     }
 
-     /**
 
-      * 开启从底层过程获取输出和错误输出。
 
-      * @access public
 
-      * @return Process
 
-      * @throws \RuntimeException
 
-      */
 
-     public function enableOutput()
 
-     {
 
-         if ($this->isRunning()) {
 
-             throw new \RuntimeException('Enabling output while the process is running is not possible.');
 
-         }
 
-         $this->outputDisabled = false;
 
-         return $this;
 
-     }
 
-     /**
 
-      * 输出是否禁用
 
-      * @access public
 
-      * @return bool
 
-      */
 
-     public function isOutputDisabled()
 
-     {
 
-         return $this->outputDisabled;
 
-     }
 
-     /**
 
-      * 获取当前的输出管道
 
-      * @access public
 
-      * @return string
 
-      * @throws \LogicException
 
-      * @api
 
-      */
 
-     public function getOutput()
 
-     {
 
-         if ($this->outputDisabled) {
 
-             throw new \LogicException('Output has been disabled.');
 
-         }
 
-         $this->requireProcessIsStarted(__FUNCTION__);
 
-         $this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
 
-         return $this->stdout;
 
-     }
 
-     /**
 
-      * 以增量方式返回的输出结果。
 
-      * @access public
 
-      * @return string
 
-      */
 
-     public function getIncrementalOutput()
 
-     {
 
-         $this->requireProcessIsStarted(__FUNCTION__);
 
-         $data = $this->getOutput();
 
-         $latest = substr($data, $this->incrementalOutputOffset);
 
-         if (false === $latest) {
 
-             return '';
 
-         }
 
-         $this->incrementalOutputOffset = strlen($data);
 
-         return $latest;
 
-     }
 
-     /**
 
-      * 清空输出
 
-      * @access public
 
-      * @return Process
 
-      */
 
-     public function clearOutput()
 
-     {
 
-         $this->stdout                  = '';
 
-         $this->incrementalOutputOffset = 0;
 
-         return $this;
 
-     }
 
-     /**
 
-      * 返回当前的错误输出的过程 (STDERR)。
 
-      * @access public
 
-      * @return string
 
-      */
 
-     public function getErrorOutput()
 
-     {
 
-         if ($this->outputDisabled) {
 
-             throw new \LogicException('Output has been disabled.');
 
-         }
 
-         $this->requireProcessIsStarted(__FUNCTION__);
 
-         $this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
 
-         return $this->stderr;
 
-     }
 
-     /**
 
-      * 以增量方式返回 errorOutput
 
-      * @access public
 
-      * @return string
 
-      */
 
-     public function getIncrementalErrorOutput()
 
-     {
 
-         $this->requireProcessIsStarted(__FUNCTION__);
 
-         $data = $this->getErrorOutput();
 
-         $latest = substr($data, $this->incrementalErrorOutputOffset);
 
-         if (false === $latest) {
 
-             return '';
 
-         }
 
-         $this->incrementalErrorOutputOffset = strlen($data);
 
-         return $latest;
 
-     }
 
-     /**
 
-      * 清空 errorOutput
 
-      * @access public
 
-      * @return Process
 
-      */
 
-     public function clearErrorOutput()
 
-     {
 
-         $this->stderr                       = '';
 
-         $this->incrementalErrorOutputOffset = 0;
 
-         return $this;
 
-     }
 
-     /**
 
-      * 获取退出码
 
-      * @access public
 
-      * @return null|int
 
-      */
 
-     public function getExitCode()
 
-     {
 
-         if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
 
-             throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
 
-         }
 
-         $this->updateStatus(false);
 
-         return $this->exitcode;
 
-     }
 
-     /**
 
-      * 获取退出文本
 
-      * @access public
 
-      * @return null|string
 
-      */
 
-     public function getExitCodeText()
 
-     {
 
-         if (null === $exitcode = $this->getExitCode()) {
 
-             return;
 
-         }
 
-         return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
 
-     }
 
-     /**
 
-      * 检查是否成功
 
-      * @access public
 
-      * @return bool
 
-      */
 
-     public function isSuccessful()
 
-     {
 
-         return 0 === $this->getExitCode();
 
-     }
 
-     /**
 
-      * 是否未捕获的信号已被终止子进程
 
-      * @access public
 
-      * @return bool
 
-      */
 
-     public function hasBeenSignaled()
 
-     {
 
-         $this->requireProcessIsTerminated(__FUNCTION__);
 
-         if ($this->isSigchildEnabled()) {
 
-             throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
 
-         }
 
-         $this->updateStatus(false);
 
-         return $this->processInformation['signaled'];
 
-     }
 
-     /**
 
-      * 返回导致子进程终止其执行的数。
 
-      * @access public
 
-      * @return int
 
-      */
 
-     public function getTermSignal()
 
-     {
 
-         $this->requireProcessIsTerminated(__FUNCTION__);
 
-         if ($this->isSigchildEnabled()) {
 
-             throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
 
-         }
 
-         $this->updateStatus(false);
 
-         return $this->processInformation['termsig'];
 
-     }
 
-     /**
 
-      * 检查子进程信号是否已停止
 
-      * @access public
 
-      * @return bool
 
-      */
 
-     public function hasBeenStopped()
 
-     {
 
-         $this->requireProcessIsTerminated(__FUNCTION__);
 
-         $this->updateStatus(false);
 
-         return $this->processInformation['stopped'];
 
-     }
 
-     /**
 
-      * 返回导致子进程停止其执行的数。
 
-      * @access public
 
-      * @return int
 
-      */
 
-     public function getStopSignal()
 
-     {
 
-         $this->requireProcessIsTerminated(__FUNCTION__);
 
-         $this->updateStatus(false);
 
-         return $this->processInformation['stopsig'];
 
-     }
 
-     /**
 
-      * 检查是否正在运行
 
-      * @access public
 
-      * @return bool
 
-      */
 
-     public function isRunning()
 
-     {
 
-         if (self::STATUS_STARTED !== $this->status) {
 
-             return false;
 
-         }
 
-         $this->updateStatus(false);
 
-         return $this->processInformation['running'];
 
-     }
 
-     /**
 
-      * 检查是否已开始
 
-      * @access public
 
-      * @return bool
 
-      */
 
-     public function isStarted()
 
-     {
 
-         return self::STATUS_READY != $this->status;
 
-     }
 
-     /**
 
-      * 检查是否已终止
 
-      * @access public
 
-      * @return bool
 
-      */
 
-     public function isTerminated()
 
-     {
 
-         $this->updateStatus(false);
 
-         return self::STATUS_TERMINATED == $this->status;
 
-     }
 
-     /**
 
-      * 获取当前的状态
 
-      * @access public
 
-      * @return string
 
-      */
 
-     public function getStatus()
 
-     {
 
-         $this->updateStatus(false);
 
-         return $this->status;
 
-     }
 
-     /**
 
-      * 终止进程
 
-      * @access public
 
-      */
 
-     public function stop()
 
-     {
 
-         if ($this->isRunning()) {
 
-             if ('\\' === DIRECTORY_SEPARATOR && !$this->isSigchildEnabled()) {
 
-                 exec(sprintf('taskkill /F /T /PID %d 2>&1', $this->getPid()), $output, $exitCode);
 
-                 if ($exitCode > 0) {
 
-                     throw new \RuntimeException('Unable to kill the process');
 
-                 }
 
-             } else {
 
-                 $pids = preg_split('/\s+/', `ps -o pid --no-heading --ppid {$this->getPid()}`);
 
-                 foreach ($pids as $pid) {
 
-                     if (is_numeric($pid)) {
 
-                         posix_kill($pid, 9);
 
-                     }
 
-                 }
 
-             }
 
-         }
 
-         $this->updateStatus(false);
 
-         if ($this->processInformation['running']) {
 
-             $this->close();
 
-         }
 
-         return $this->exitcode;
 
-     }
 
-     /**
 
-      * 添加一行输出
 
-      * @access public
 
-      * @param string $line
 
-      */
 
-     public function addOutput($line)
 
- {
 
-         $this->lastOutputTime = microtime(true);
 
-         $this->stdout .= $line;
 
-     }
 
-     /**
 
-      * 添加一行错误输出
 
-      * @access public
 
-      * @param string $line
 
-      */
 
-     public function addErrorOutput($line)
 
- {
 
-         $this->lastOutputTime = microtime(true);
 
-         $this->stderr .= $line;
 
-     }
 
-     /**
 
-      * 获取被执行的指令
 
-      * @access public
 
-      * @return string
 
-      */
 
-     public function getCommandLine()
 
- {
 
-         return $this->commandline;
 
-     }
 
-     /**
 
-      * 设置指令
 
-      * @access public
 
-      * @param string $commandline
 
-      * @return self
 
-      */
 
-     public function setCommandLine($commandline)
 
- {
 
-         $this->commandline = $commandline;
 
-         return $this;
 
-     }
 
-     /**
 
-      * 获取超时时间
 
-      * @access public
 
-      * @return float|null
 
-      */
 
-     public function getTimeout()
 
- {
 
-         return $this->timeout;
 
-     }
 
-     /**
 
-      * 获取idle超时时间
 
-      * @access public
 
-      * @return float|null
 
-      */
 
-     public function getIdleTimeout()
 
- {
 
-         return $this->idleTimeout;
 
-     }
 
-     /**
 
-      * 设置超时时间
 
-      * @access public
 
-      * @param  int|float|null $timeout
 
-      * @return self
 
-      */
 
-     public function setTimeout($timeout)
 
- {
 
-         $this->timeout = $this->validateTimeout($timeout);
 
-         return $this;
 
-     }
 
-     /**
 
-      * 设置idle超时时间
 
-      * @access public
 
-      * @param  int|float|null $timeout
 
-      * @return self
 
-      */
 
-     public function setIdleTimeout($timeout)
 
- {
 
-         if (null !== $timeout && $this->outputDisabled) {
 
-             throw new \LogicException('Idle timeout can not be set while the output is disabled.');
 
-         }
 
-         $this->idleTimeout = $this->validateTimeout($timeout);
 
-         return $this;
 
-     }
 
-     /**
 
-      * 设置TTY
 
-      * @access public
 
-      * @param  bool $tty
 
-      * @return self
 
-      */
 
-     public function setTty($tty)
 
- {
 
-         if ('\\' === DIRECTORY_SEPARATOR && $tty) {
 
-             throw new \RuntimeException('TTY mode is not supported on Windows platform.');
 
-         }
 
-         if ($tty && (!file_exists('/dev/tty') || !is_readable('/dev/tty'))) {
 
-             throw new \RuntimeException('TTY mode requires /dev/tty to be readable.');
 
-         }
 
-         $this->tty = (bool) $tty;
 
-         return $this;
 
-     }
 
-     /**
 
-      * 检查是否是tty模式
 
-      * @access public
 
-      * @return bool
 
-      */
 
-     public function isTty()
 
- {
 
-         return $this->tty;
 
-     }
 
-     /**
 
-      * 设置pty模式
 
-      * @access public
 
-      * @param  bool $bool
 
-      * @return self
 
-      */
 
-     public function setPty($bool)
 
- {
 
-         $this->pty = (bool) $bool;
 
-         return $this;
 
-     }
 
-     /**
 
-      * 是否是pty模式
 
-      * @access public
 
-      * @return bool
 
-      */
 
-     public function isPty()
 
- {
 
-         return $this->pty;
 
-     }
 
-     /**
 
-      * 获取工作目录
 
-      * @access public
 
-      * @return string|null
 
-      */
 
-     public function getWorkingDirectory()
 
- {
 
-         if (null === $this->cwd) {
 
-             return getcwd() ?: null;
 
-         }
 
-         return $this->cwd;
 
-     }
 
-     /**
 
-      * 设置工作目录
 
-      * @access public
 
-      * @param  string $cwd
 
-      * @return self
 
-      */
 
-     public function setWorkingDirectory($cwd)
 
- {
 
-         $this->cwd = $cwd;
 
-         return $this;
 
-     }
 
-     /**
 
-      * 获取环境变量
 
-      * @access public
 
-      * @return array
 
-      */
 
-     public function getEnv()
 
- {
 
-         return $this->env;
 
-     }
 
-     /**
 
-      * 设置环境变量
 
-      * @access public
 
-      * @param  array $env
 
-      * @return self
 
-      */
 
-     public function setEnv(array $env)
 
- {
 
-         $env = array_filter($env, function ($value) {
 
-             return !is_array($value);
 
-         });
 
-         $this->env = [];
 
-         foreach ($env as $key => $value) {
 
-             $this->env[(binary) $key] = (binary) $value;
 
-         }
 
-         return $this;
 
-     }
 
-     /**
 
-      * 获取输入
 
-      * @access public
 
-      * @return null|string
 
-      */
 
-     public function getInput()
 
- {
 
-         return $this->input;
 
-     }
 
-     /**
 
-      * 设置输入
 
-      * @access public
 
-      * @param  mixed $input
 
-      * @return self
 
-      */
 
-     public function setInput($input)
 
- {
 
-         if ($this->isRunning()) {
 
-             throw new \LogicException('Input can not be set while the process is running.');
 
-         }
 
-         $this->input = Utils::validateInput(sprintf('%s::%s', __CLASS__, __FUNCTION__), $input);
 
-         return $this;
 
-     }
 
-     /**
 
-      * 获取proc_open的选项
 
-      * @access public
 
-      * @return array
 
-      */
 
-     public function getOptions()
 
- {
 
-         return $this->options;
 
-     }
 
-     /**
 
-      * 设置proc_open的选项
 
-      * @access public
 
-      * @param  array $options
 
-      * @return self
 
-      */
 
-     public function setOptions(array $options)
 
- {
 
-         $this->options = $options;
 
-         return $this;
 
-     }
 
-     /**
 
-      * 是否兼容windows
 
-      * @access public
 
-      * @return bool
 
-      */
 
-     public function getEnhanceWindowsCompatibility()
 
- {
 
-         return $this->enhanceWindowsCompatibility;
 
-     }
 
-     /**
 
-      * 设置是否兼容windows
 
-      * @access public
 
-      * @param  bool $enhance
 
-      * @return self
 
-      */
 
-     public function setEnhanceWindowsCompatibility($enhance)
 
- {
 
-         $this->enhanceWindowsCompatibility = (bool) $enhance;
 
-         return $this;
 
-     }
 
-     /**
 
-      * 返回是否 sigchild 兼容模式激活
 
-      * @access public
 
-      * @return bool
 
-      */
 
-     public function getEnhanceSigchildCompatibility()
 
- {
 
-         return $this->enhanceSigchildCompatibility;
 
-     }
 
-     /**
 
-      * 激活 sigchild 兼容性模式。
 
-      * @access public
 
-      * @param  bool $enhance
 
-      * @return self
 
-      */
 
-     public function setEnhanceSigchildCompatibility($enhance)
 
- {
 
-         $this->enhanceSigchildCompatibility = (bool) $enhance;
 
-         return $this;
 
-     }
 
-     /**
 
-      * 是否超时
 
-      */
 
-     public function checkTimeout()
 
- {
 
-         if (self::STATUS_STARTED !== $this->status) {
 
-             return;
 
-         }
 
-         if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
 
-             $this->stop();
 
-             throw new ProcessTimeoutException($this, ProcessTimeoutException::TYPE_GENERAL);
 
-         }
 
-         if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
 
-             $this->stop();
 
-             throw new ProcessTimeoutException($this, ProcessTimeoutException::TYPE_IDLE);
 
-         }
 
-     }
 
-     /**
 
-      * 是否支持pty
 
-      * @access public
 
-      * @return bool
 
-      */
 
-     public static function isPtySupported()
 
- {
 
-         static $result;
 
-         if (null !== $result) {
 
-             return $result;
 
-         }
 
-         if ('\\' === DIRECTORY_SEPARATOR) {
 
-             return $result = false;
 
-         }
 
-         $proc = @proc_open('echo 1', [['pty'], ['pty'], ['pty']], $pipes);
 
-         if (is_resource($proc)) {
 
-             proc_close($proc);
 
-             return $result = true;
 
-         }
 
-         return $result = false;
 
-     }
 
-     /**
 
-      * 创建所需的 proc_open 的描述符
 
-      * @access private
 
-      * @return array
 
-      */
 
-     private function getDescriptors()
 
- {
 
-         if ('\\' === DIRECTORY_SEPARATOR) {
 
-             $this->processPipes = WindowsPipes::create($this, $this->input);
 
-         } else {
 
-             $this->processPipes = UnixPipes::create($this, $this->input);
 
-         }
 
-         $descriptors = $this->processPipes->getDescriptors($this->outputDisabled);
 
-         if (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
 
-             $descriptors = array_merge($descriptors, [['pipe', 'w']]);
 
-             $this->commandline = '(' . $this->commandline . ') 3>/dev/null; code=$?; echo $code >&3; exit $code';
 
-         }
 
-         return $descriptors;
 
-     }
 
-     /**
 
-      * 建立 wait () 使用的回调。
 
-      * @access protected
 
-      * @param  callable|null $callback
 
-      * @return callable
 
-      */
 
-     protected function buildCallback($callback)
 
- {
 
-         $out      = self::OUT;
 
-         $callback = function ($type, $data) use ($callback, $out) {
 
-             if ($out == $type) {
 
-                 $this->addOutput($data);
 
-             } else {
 
-                 $this->addErrorOutput($data);
 
-             }
 
-             if (null !== $callback) {
 
-                 call_user_func($callback, $type, $data);
 
-             }
 
-         };
 
-         return $callback;
 
-     }
 
-     /**
 
-      * 更新状态
 
-      * @access protected
 
-      * @param bool $blocking
 
-      */
 
-     protected function updateStatus($blocking)
 
- {
 
-         if (self::STATUS_STARTED !== $this->status) {
 
-             return;
 
-         }
 
-         $this->processInformation = proc_get_status($this->process);
 
-         $this->captureExitCode();
 
-         $this->readPipes($blocking, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
 
-         if (!$this->processInformation['running']) {
 
-             $this->close();
 
-         }
 
-     }
 
-     /**
 
-      * 是否开启 '--enable-sigchild'
 
-      * @access protected
 
-      * @return bool
 
-      */
 
-     protected function isSigchildEnabled()
 
- {
 
-         if (null !== self::$sigchild) {
 
-             return self::$sigchild;
 
-         }
 
-         if (!function_exists('phpinfo')) {
 
-             return self::$sigchild = false;
 
-         }
 
-         ob_start();
 
-         phpinfo(INFO_GENERAL);
 
-         return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
 
-     }
 
-     /**
 
-      * 验证是否超时
 
-      * @access private
 
-      * @param  int|float|null $timeout
 
-      * @return float|null
 
-      */
 
-     private function validateTimeout($timeout)
 
- {
 
-         $timeout = (float) $timeout;
 
-         if (0.0 === $timeout) {
 
-             $timeout = null;
 
-         } elseif ($timeout < 0) {
 
-             throw new \InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
 
-         }
 
-         return $timeout;
 
-     }
 
-     /**
 
-      * 读取pipes
 
-      * @access private
 
-      * @param  bool $blocking
 
-      * @param  bool $close
 
-      */
 
-     private function readPipes($blocking, $close)
 
- {
 
-         $result = $this->processPipes->readAndWrite($blocking, $close);
 
-         $callback = $this->callback;
 
-         foreach ($result as $type => $data) {
 
-             if (3 == $type) {
 
-                 $this->fallbackExitcode = (int) $data;
 
-             } else {
 
-                 $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data);
 
-             }
 
-         }
 
-     }
 
-     /**
 
-      * 捕获退出码
 
-      */
 
-     private function captureExitCode()
 
- {
 
-         if (isset($this->processInformation['exitcode']) && -1 != $this->processInformation['exitcode']) {
 
-             $this->exitcode = $this->processInformation['exitcode'];
 
-         }
 
-     }
 
-     /**
 
-      * 关闭资源
 
-      * @access private
 
-      * @return int 退出码
 
-      */
 
-     private function close()
 
- {
 
-         $this->processPipes->close();
 
-         if (is_resource($this->process)) {
 
-             $exitcode = proc_close($this->process);
 
-         } else {
 
-             $exitcode = -1;
 
-         }
 
-         $this->exitcode = -1 !== $exitcode ? $exitcode : (null !== $this->exitcode ? $this->exitcode : -1);
 
-         $this->status   = self::STATUS_TERMINATED;
 
-         if (-1 === $this->exitcode && null !== $this->fallbackExitcode) {
 
-             $this->exitcode = $this->fallbackExitcode;
 
-         } elseif (-1 === $this->exitcode && $this->processInformation['signaled']
 
-             && 0 < $this->processInformation['termsig']
 
-         ) {
 
-             $this->exitcode = 128 + $this->processInformation['termsig'];
 
-         }
 
-         return $this->exitcode;
 
-     }
 
-     /**
 
-      * 重置数据
 
-      */
 
-     private function resetProcessData()
 
- {
 
-         $this->starttime                    = null;
 
-         $this->callback                     = null;
 
-         $this->exitcode                     = null;
 
-         $this->fallbackExitcode             = null;
 
-         $this->processInformation           = null;
 
-         $this->stdout                       = null;
 
-         $this->stderr                       = null;
 
-         $this->process                      = null;
 
-         $this->latestSignal                 = null;
 
-         $this->status                       = self::STATUS_READY;
 
-         $this->incrementalOutputOffset      = 0;
 
-         $this->incrementalErrorOutputOffset = 0;
 
-     }
 
-     /**
 
-      * 将一个 POSIX 信号发送到进程中。
 
-      * @access private
 
-      * @param  int  $signal
 
-      * @param  bool $throwException
 
-      * @return bool
 
-      */
 
-     private function doSignal($signal, $throwException)
 
- {
 
-         if (!$this->isRunning()) {
 
-             if ($throwException) {
 
-                 throw new \LogicException('Can not send signal on a non running process.');
 
-             }
 
-             return false;
 
-         }
 
-         if ($this->isSigchildEnabled()) {
 
-             if ($throwException) {
 
-                 throw new \RuntimeException('This PHP has been compiled with --enable-sigchild. The process can not be signaled.');
 
-             }
 
-             return false;
 
-         }
 
-         if (true !== @proc_terminate($this->process, $signal)) {
 
-             if ($throwException) {
 
-                 throw new \RuntimeException(sprintf('Error while sending signal `%s`.', $signal));
 
-             }
 
-             return false;
 
-         }
 
-         $this->latestSignal = $signal;
 
-         return true;
 
-     }
 
-     /**
 
-      * 确保进程已经开启
 
-      * @access private
 
-      * @param  string $functionName
 
-      */
 
-     private function requireProcessIsStarted($functionName)
 
- {
 
-         if (!$this->isStarted()) {
 
-             throw new \LogicException(sprintf('Process must be started before calling %s.', $functionName));
 
-         }
 
-     }
 
-     /**
 
-      * 确保进程已经终止
 
-      * @access private
 
-      * @param  string $functionName
 
-      */
 
-     private function requireProcessIsTerminated($functionName)
 
- {
 
-         if (!$this->isTerminated()) {
 
-             throw new \LogicException(sprintf('Process must be terminated before calling %s.', $functionName));
 
-         }
 
-     }
 
- }
 
 
  |