php使用goto实现自动重启swoole、reactphp、workerman服务的代码
在平时使用swoole进行开发中,常常遇到这种问题,改了代码之后,手动ctrl+c中断服务,再敲命令重启服务。频繁地重启,感觉心很累。
php提供了inotify扩展,调用linux的inotify系统调用,监控文件的变化.
这时候就产生了一个想法,我开一个主进程监控文件变化,再开一个子进程运行swoole服务。主进程监听到文件变化之后,干掉子进程,然后再开一个子进程运行swoole服务. 子进程如果想优雅地退出,安装个信号处理器,在退出之前做一些操作。
<?php //index.php require './vendor/autoload.php'; Restart: $pid = pcntl_fork(); if ($pid > 0) { $fd = inotify_init(); $watch_descriptor = inotify_add_watch($fd, './src/', IN_MODIFY); $events = inotify_read($fd); posix_kill($pid, SIGTERM); fclose($fd); pcntl_wait($status); goto Restart; } elseif ($pid == 0) { \Church\Application::run(); } else { exit(0); }
<?php namespace Church; /** use Psr\Http\Message\ServerRequestInterface; use React\Http\Response; use React\Http\Server; **/ class Application { public static function run() { /** $loop = \React\EventLoop\Factory::create(); $loop->addSignal(SIGTERM, function() use ($loop) { $loop->stop(); }); $server = new Server(function (ServerRequestInterface $request) { return new Response( 200, array( 'Content-Type' => 'text/plain' ), "Hello World1!\n" ); }); $socket = new \React\Socket\Server(8080, $loop); $server->listen($socket); $loop->run(); **/ //高性能HTTP服务器 $http = new \Swoole\Http\Server("127.0.0.1", 9501); $http->on("start", function ($server) { echo "Swoole http server is started at http://127.0.0.1:9501\n"; }); $http->on("request", function ($request, $response) { $response->header("Content-Type", "text/plain"); $response->end("Hello World1\n"); }); $http->start(); } }
个人觉得这里最优雅的实现方式应该是用GOTO了。
相关推荐
zyyjay 2020-11-09
xuebingnan 2020-11-05
samtrue 2020-11-22
stefan0 2020-11-22
yifangs 2020-10-13
songshijiazuaa 2020-09-24
hebiwtc 2020-09-18
天步 2020-09-17
83911535 2020-11-13
whatsyourname 2020-11-13
zhouyuqi 2020-11-10
Noneyes 2020-11-10
mathchao 2020-10-28
王志龙 2020-10-28
wwwsurfphpseocom 2020-10-28
diskingchuan 2020-10-23
savorTheFlavor 2020-10-23