3){ echo "invalid argument action. expected start|stop|restart|reload [-d]\n"; return false; } if(count($argv) == 3 && $argv[2] == '-d'){ $this->daemon = 1; } $action = $argv[1]; $this->init(); if (in_array($action, ['start', 'stop', 'reload', 'restart'])) { $this->$action(); } else { echo "invalid argument action:{$action}, expected start|stop|restart|reload .\n"; } } protected function init() { $this->config = []; if (empty($this->config['pid_file'])) { $this->config['pid_file'] = '/usr/local/swoole.pid'; } // 避免pid混乱 // $this->config['pid_file'] .= '_' . $this->getPort(); } /** * 启动server * @access protected * @return void */ protected function start() { $pid = $this->getMasterPid(); if ($this->isRunning($pid)) { echo "swoole server process is already running\n"; return false; } echo "---------------------------------------------- SERVER STATUS ----------------------------------------------------\n"; echo "starting swoole server...\n"; echo ("swoole ws server started: \n"); echo("you can exit with `CTRL-C`\n"); echo "---------------------------------------------- SERVER STATUS ----------------------------------------------------\n"; new Websocket($this->daemon); } /** * 平滑重启server */ protected function reload() { $pid = $this->getMasterPid(); if (!$this->isRunning($pid)) { echo "no swoole server process running.\n"; return false; } echo "reloading swoole server...\n"; \swoole_process::kill($pid, SIGUSR1); echo "> success\n"; } /** * 停止server */ protected function stop() { $pid = $this->getMasterPid(); if (!$this->isRunning($pid)) { echo "no swoole server process running.\n"; return false; } echo "stopping swoole server...\n"; \swoole_process::kill($pid, SIGTERM); $this->removePid(); echo "> success\n"; } /** * 重启server */ protected function restart() { $pid = $this->getMasterPid(); if ($this->isRunning($pid)) { $this->stop(); } sleep(1); $this->start($this->daemon); } /** * 获取主进程PID */ protected function getMasterPid() { $pidFile = $this->config['pid_file']; if (is_file($pidFile)) { $masterPid = (int) file_get_contents($pidFile); } else { $masterPid = 0; } return $masterPid; } /** * 删除PID文件 */ protected function removePid() { $masterPid = $this->config['pid_file']; if (is_file($masterPid)) { unlink($masterPid); } } /** * 判断PID是否在运行 */ protected function isRunning($pid) { if (empty($pid)) { return false; } return \swoole_process::kill($pid, 0); } }