首頁  >  文章  >  後端開發  >  PHP的pcntl進程控制之多進程消費模型

PHP的pcntl進程控制之多進程消費模型

不言
不言原創
2018-07-06 17:44:511218瀏覽

這篇文章主要介紹了關於PHP的pcntl進程控制之多進程消費模型,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

多進程消費模型

父進程等待並控制子進程的退出

思路整理

父進程開啟後,直接取得到子進程的pid,然後存入child數組,子進程fork出來後直接開啟業務消費代碼,然後exit(0)退出,然後父進程pcntl_wait等待子進程退出,全部退出後父進程結束

代碼

const NEWLINE = "\n\n";

if (strtolower(php_sapi_name()) != 'cli') {
    die("请在cli模式下运行");
}

$bizPath = "./childBiz/";

if (!is_dir($bizPath)) {
    @mkdir($bizPath, 0755, true);
}

$child = [];

$index = 0;
$loop = 10; //子进程的数量

//如果是资源类型的变量,父子进程会共享
//$f = fopen("./pcntl_fork_2.php", "r");

while ($index < $loop) {

    echo "当前进程:" . getmypid() . NEWLINE;

    $pid = pcntl_fork(); //fork出子进程

    //fork后父进程会走自己的逻辑,子进程从处开始走自己的逻辑,堆栈信息会完全复制给子进程内存空间,父子进程相互独立

    if ($pid == -1) { // 创建错误,返回-1

        die(&#39;进程fork失败&#39;);

    } else if ($pid) { // $pid > 0, 如果fork成功,返回子进程id

        //获取创建的子进程
        $child[$pid] = $pid;
        echo "{$pid} child create!" . microtime(true) . NEWLINE;

    } else { // $pid = 0

        // 子进程逻辑
        $sleepTime = rand(5, 18);
        sleep($sleepTime);
        $time = microtime(true);
        file_put_contents($bizPath.getmypid().".log", $time . ":" . $index . PHP_EOL, FILE_APPEND);
        exit(0);
    }
    $index++;
}

while (count($child)) {
    //阻塞等待
    $pid = pcntl_wait($status);
    $time = microtime(true);
    file_put_contents("./father.log", $time . ":" . $pid . ":" . $status . PHP_EOL, FILE_APPEND);
    if ($pid > 0) {
        unset($child[$pid]);
    }
    if ($pid == -1) {
        unset($child);
    }
//    foreach ($child as $k => $pid) {
//        //不阻塞循环判断 WNOHANG表示如果没有子进程退出立刻返回
//        $res = pcntl_waitpid($pid, $status, WNOHANG);
//        $time = microtime(true);
//        file_put_contents("./father.log", $time . ":" . $pid . ":" . $res . ":" . $status . PHP_EOL, FILE_APPEND);
//        if (-1 == $res || $res > 0) {
//            unset($child[$k]);
//        }
//    }
}

//fclose($f);
//主进程退出
exit(0);

以上就是本文的全部內容,希望對大家的學習有幫助,更多相關內容請關注PHP中文網!

相關推薦:

PHP的pcntl進程控制之pcntl_wait

PHP的pcntl進程控制之pcntl_fork

#

以上是PHP的pcntl進程控制之多進程消費模型的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn