for循环中主进程fork子进程,为什么主进程会退出?

loc1992
<?php 

    \umask(0);

    $pid = \pcntl_fork();

    if (-1 === $pid) {
        throw new Exception('Fork fail');
    } elseif ($pid > 0) {

        exit(0);
    }

    if (-1 === \posix_setsid()) {
        throw new Exception("Setsid fail");
    }

    $pid = \pcntl_fork();
    if (-1 === $pid) {
        throw new Exception("Fork fail");
    } elseif (0 !== $pid) {
        exit(0);
    }

    $stdoutFile = __DIR__."/io.log";
    global $STDERR, $STDOUT;
    // 重定向标准输出和错误输出
    fclose(STDOUT);
    fclose(STDERR);
    $STDOUT = fopen($stdoutFile, 'a');
    $STDERR = fopen($stdoutFile, 'a');

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

        if($child_pid > 0)
        {
            // 主进程
           \cli_set_process_title('test Master: '.getmypid());

        }else{
            // 子进程
            \cli_set_process_title('test Sub: '.getmypid());
            // break; // 使用break没有问题
            // 这里Worker.php源码里面也是阻塞的
            // 为什么我的这里使用阻塞,Master进程会退出,子进程变成孤儿了
            while (1) {
                $pid = getmypid();
                $ppid = posix_getppid();
                echo "pid:$pid --- ppid:$ppid".PHP_EOL;
                sleep(5);
            }
        }
    }

代码是抽取Worker类的,搞不明白为什么主进程会退出,求指点。

2537 1 0
1个回答

loc1992

搞懂了,主进程没有阻塞直接执行完脚本就退出了。

  • 暂无评论
年代过于久远,无法发表回答
🔝