php logo
PHP

php多进程编程

<?php
//  建议php5.3以上,代码中自行调用pcntl_signal_dispatch();
if (!function_exists("pcntl_signal_dispatch")) {
    declare(ticks=1);
}
pcntl_signal(SIGCHLD, SIG_IGN); // 注册信号处理函数  如果父进程不关心子进程什么时候结束,设为SIG_IGN, 子进程结束后,内核会回收,并不再给父进程发送信号

$child_pids = [];
for ($i = 0; $i<3; $i++) {
    $child_pid = pcntl_fork();

    switch ($child_pid) {
        case -1:
            exit('fork fail!');
            break;
        case 0:
            echo '子进程开始,PID:' . getmypid() . PHP_EOL;
            sleep(rand(1,5));
            echo '子进程结束,PID:' . getmypid() . PHP_EOL;
            exit();
            break;
        default:
            $child_pids[] = $child_pid;
            echo '父进程-runing,PID:' . getmypid() . PHP_EOL;
            break;
    }
}

while (count($child_pids)) {
    foreach ($child_pids as $key => $child_pid) {
        if (!function_exists("pcntl_signal_dispatch")) {
            pcntl_signal_dispatch();
        }
        //$res = pcntl_wait($status, WNOHANG);
        $res = pcntl_waitpid($child_pid, $status, WNOHANG);
        if ($res == -1 || $res > 0) {
            echo '子进程退出, PID:' . $child_pid . PHP_EOL;
            unset($child_pids[$key]);
        } else {
            usleep(500000);
            echo 'WAIT' . PHP_EOL;
        }
    }
}
echo '父进程退出' . PHP_EOL;

精品课程


guest

0 评论
内联反馈
查看所有评论