pcntl_fork()在PHPUnit测试中的用法

pcntl_fork()在PHPUnit测试中的用法,php,phpunit,fork,pcntl,Php,Phpunit,Fork,Pcntl,我对PHPUnit中的pcntl_fork()用法有一些问题。我正在执行这个代码 class ForkTest extends PHPUnit_Framework_TestCase { public function test1() { print('Start test with pid '.posix_getpid()."\n"); $pids = []; for ($count = 0; $count < 3; ++$cou

我对PHPUnit中的pcntl_fork()用法有一些问题。我正在执行这个代码

class ForkTest extends PHPUnit_Framework_TestCase {
    public function test1() {
        print('Start test with pid '.posix_getpid()."\n");

        $pids = [];

        for ($count = 0; $count < 3; ++$count) {
            $pids[$count] = pcntl_fork();
            if (-1 == $pids[$count]) {
                die("It's a trap, iteration $count\n");
            } else if (!$pids[$count]) {
                print("I'm child with pid ".posix_getpid()."\n");
                exit();
            }
            print('Parent: after fork, new child: '.$pids[$count]."\n");
        }

        for ($count = 0; $count < 3; ++$count) {
            $status = 0;
            if ($pids[$count] != pcntl_waitpid($pids[$count], $status)) {
                die("Error with wait pid $count.\n");
            } else {
                print('Process with pid '.$pids[$count]." finished\n");
            }
        }
    }
}
但我期望这样(我在不使用PHPUnit的情况下运行测试时得到):


这就是PHPUnit的预期行为?有什么方法可以修复它吗?

PHPUnit不能保证测试将按特定顺序执行,因此您应该尽量不要依赖于此。我没有看到测试代码来理解为什么会出现多次,但我猜您可能多次调用test1()函数。我看到了相同的行为。可能是PHPUnit的输出缓冲造成的。我不知道缓冲区将如何在进程之间交互。@DavidHarkness,谢谢,我自己也不明白。在print()调用之后调用ob_flush()将导致“良好”输出
Start test with pid 15886
Parent: after fork, new child: 15887
Parent: after fork, new child: 15888
I'm child with pid 15889
Start test with pid 15886
Parent: after fork, new child: 15887
I'm child with pid 15888
Start test with pid 15886
I'm child with pid 15887
.Start test with pid 15886
Parent: after fork, new child: 15887
Parent: after fork, new child: 15888
Parent: after fork, new child: 15889
Process with pid 15887 finished
Process with pid 15888 finished
Process with pid 15889 finished
Start test with pid 15907
Parent: after fork, new child: 15908
Parent: after fork, new child: 15909
Parent: after fork, new child: 15910
I'm child with pid 15910
I'm child with pid 15909
I'm child with pid 15908
Process with pid 15908 finished
Process with pid 15909 finished
Process with pid 15910 finished