swoole 父子进程间通信

<?php
/**
 * 场景:
 * 监控订单表状态 父子进程通信
 * 一个主进程 两个子进程实现
 */

//设置主进程名
echo ‘主进程id:‘ . posix_getpid() . PHP_EOL;
cli_set_process_title(‘php_main‘);

//1、此子进程用于监听数据的改变
$process1 = new Swoole\Process(function (\Swoole\Process $process) {
//    cli_set_process_title(‘php_child‘);
    $process->name(‘php_child1‘);
    $pdo = new PDO(‘mysql:host=mysql;dbname=test‘, ‘root‘, ‘root‘);

    while (true) {
        $statement = $pdo->query(‘select * from `order` where is_pay=1 and is_notice=0 order by id desc‘);
        $data = $statement->fetch(PDO::FETCH_ASSOC);
        if ($data) {
            //向主进程发送消息
            $process->write(‘php_child1发送‘ . $data[‘client_name‘] . ‘已支付 ‘);
            $pdo->exec(‘update `order` set is_notice=1 where id=‘ . $data[‘id‘]);
        }
        sleep(3);
    }
}, false, SOCK_STREAM, true);
echo ‘子进程1 id:‘ . $process1->start() . PHP_EOL;

//2、此子进程用于发送邮件
$process2 = new Swoole\Process(function (\Swoole\Process $process) {
    $process->name(‘php_child2‘);
    while (true) {
        $orderInfo = $process->read();
        if ($orderInfo) {
            echo $orderInfo;
            echo ‘php_child2发送邮件‘ . PHP_EOL;
        }
        sleep(3);
    }
}, false, SOCK_STREAM, true);
echo ‘子进程2 id:‘ . $process2->start() . PHP_EOL;


while (true) {
    //主进程读取子进程1中的消息
    $orderInfo = $process1->read();
    if ($orderInfo) {
        //主进程发送数据给子进程2
        $process2->write($orderInfo);
    }
    sleep(3);
}

//\Swoole\Process::wait();
//使用Process作为监控父进程,创建管理子进程时,父类必须注册信号SIGCHLD对退出的进程执行wait,否则子进程退出时会变成僵尸进程
Swoole\Process::signal(SIGTERM, function ($signo) {
    echo "shutdown.";
});
 

相关推荐