[TOC] ## demo `server.php` ``` /** * 只支持linux */ class Process{ private $pid; private $command; public $errorMsg =''; private $pidFile='process.pid'; /** * Process constructor. * @param string $pidfile 每个 file 文件存储一个 后台命令 */ public function __construct($pidfile=''){ if($pidfile) { $this->pidFile = $pidfile; } //设置获取pid $this->getPidByFile(); } private function runCom(){ $command = 'nohup '.$this->command.' > /dev/null 2>&1 & echo $!'; exec($command ,$op); if(!$op[0]){ $this->errorMsg="runCom 后无法获取 pid ".json_encode($op,JSON_UNESCAPED_UNICODE); return false; } $this->pid = (int)$op[0]; if(!$this->savePidByFile()){ $this->errorMsg="pid 无法保存到文件"; return false; } return true; } private function setPid($pid){ $this->pid = $pid; } public function getPid(){ return $this->pid; } public function status(){ $command = 'ps -p '.$this->pid; exec($command,$op); if (!$op[1]){ return false; } return true; } public function start($cmd=''){ if(!$cmd) { $this->errorMsg="运行指令为空"; return false; } $this->command=$cmd; if($this->status()){ return true; //已启动 } if(!$this->runCom()){ return false; } return true; } public function stop(){ if(!$this->pid) { $this->errorMsg="无法找到 pid 程序已经停止"; return false; } $command = 'kill -9 '.$this->pid; exec($command); if ($this->status() !== false){ return false; } if(!$this->delPidByFile()){ $this->errorMsg="删除pid失败"; return false; } return true; } private function savePidByFile(){ return file_put_contents($this->pidFile, $this->getPid())!==false; } private function getPidByFile(){ $pid = file_get_contents($this->pidFile); $this->setPid($pid); } private function delPidByFile(){ return file_put_contents($this->pidFile,'')!==false; } } /* ============== 测试代码 ============== */ //http://192.168.1.4:8002/test.php?type=0 $type = (int)$_GET['type'];// type 0=停止,1=开始 2=重启启动 3 查看状态 $process = (new Process("process.pid")); $cmd = "php test1.php"; switch($type){ case 0: //可能已经停止,无效判断停止失败 $process->stop(); print_log("stop success"); break; case 1: if(!$process->start($cmd)){ print_log("start failed " .$process->errorMsg); } print_log("start success"); break; case 2: //可能已经停止,无效判断停止失败 $process->stop(); if(!$process->start($cmd)){ print_log("start failed " .$process->errorMsg); } print_log("restart success"); break; case 3: if($process->status()){ print_log("running"); }else{ print_log("stop !"); } break; } function print_log($msg){ echo $msg; } ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <p>服务状态: <?php echo $process->status()?"running":"stop" ;?></p> <ul> <li><a href="?type=0">停止服务器</a></li> <li><a href="?type=1">开启服务器</a></li> <li><a href="?type=2">重启服务</a></li> </ul> </body> </html> ``` test1.php ``` $i=0; while(true){ $i++; file_put_contents("1.txt", $i."\n",FILE_APPEND); sleep(1); } ```