«

php实现 master-worker 守护多进程模式的实例代码

时间:2024-2-22 14:01     作者:韩俊     分类: PHP


php实现 master-worker 守护多进程模式的实例代码。

<?php

/**
 * Class Worker
 * php实现 master-worker 守护多进程模式的实例代码
 * @link https://www.maopiaopiao.com/
 * @author www.maopiaopiao.com
 */

class Worker {

    public static $count = 2;

    public static function run() {
        static::runMaster();
        static::monitorWorkerProcess();
    }

    /**
     * 开启主进程
     * @throws Exception
     */
    public static function runMaster() {
        //确保进程有最大操作权限
        umask(0);
        $pid = pcntl_fork();
        if ($pid > 0) {
            echo "主进程进程 $pid\r\n";
            exit;
        } else if ($pid == 0) {
            if (-1 === posix_setsid()) {
                echo "setsid fail\r\n";
                throw new Exception("setsid fail");
            }
            for ($i = 0; $i < self::$count; $i++) {
                static::runWorker();
            }
            cli_set_process_title("master_process");
        } else {
            throw new Exception("创建主进程失败");
        }
    }

    /**
     * 开启子进程
     * @throws Exception
     */
    public static function runWorker() {
        umask(0);
        $pid = pcntl_fork();
        if ($pid > 0) {
            echo "创建子进程 $pid \r\n";
        } else if ($pid == 0) {
            if (-1 === posix_setsid()) {
                throw new Exception("setsid fail");
            }
            cli_set_process_title("worker_process");
            self::doJob();
        } else {
            throw new Exception("创建子进程失败");
        }

    }

    /**
     * 监控worker进程
     * @throws Exception
     */
    public static function monitorWorkerProcess() {
        while ($pid = pcntl_wait($status)) {
            if ($pid == -1) {
                break;
            } else {
                static::runWorker();
            }
        }
    }

    /**
     * 业务逻辑
     */
    public static function doJob() {
        while (1) {
            sleep(3);
            echo '进程:' . posix_getpid() . ' ' . date('Y-m-d H:i:s') . '输出' . "\r\n";
        }
    }
}

Worker::run();

标签: php php教程

热门推荐