這篇文章帶給大家的內容是關於swoole_process父子進程管道通訊的程式碼範例,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。
話不多說直接上程式碼
建立的子程序:
public function __construct() { $this->redis = Container::get(SwooleRedis::class);//获取异步redis获取更高性能 $this->process = new swoole_process(function (swoole_process $process) { return $this->process($process); }, false, SOCK_DGRAM); $this->process->name('Test_Gateway'); $this->process->useQueue(); $this->process->start();//启动子进程 } /** * 子进程处理逻辑 * @param swoole_process $process */ private function process(swoole_process $process) { $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); //异步非阻塞 $client->on("connect", function (swoole_client $cli) use ($process) { $process->write('connected'); }); $client->on("receive", function (swoole_client $cli, $data) use ($process) { $process->write($data); }); $client->on("error", function (swoole_client $cli) use ($process) { $process->write('error'); }); $client->on("close", function (swoole_client $cli) use ($process) { $process->write('close'); }); if ($client->connect('127.0.0.1', 90, -1)) { } else { $process->write('网关连接失败'); } swoole_event_add($process->pipe, function ($pipe) use ($process, $client) {//读取父进程管道消息 $client->send($process->read()); }); }
父程式onWorkerStart:
/** * @param swoole_server $serv * @param $worker_id */ public function onWorkerStart(\swoole_server $serv, $worker_id) { if ($worker_id === 0) { swoole_timer_tick(1000, function () { $this->process->write('ping'); }); $process = $this->process; swoole_event_add($process->pipe, function ($pipe) use ($process) {//获取子进程的管道消息 echo "子进程消息:" . $process->read() . PHP_EOL; }); } }
以上是swoole_process父子進程管道通訊的程式碼範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!