pcntl_fork() usage in PHPUnit tests

1k Views Asked by At

I have some problem with pcntl_fork() usage in PHPUnit. I'm executing this code

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");
            }
        }
    }
}

and I'm getting the following:

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

But I expect something like this (I got it when run my test without PHPUnit usage):

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

So, this is expected behavior of PHPUnit? And there are any way to fix it?

0

There are 0 best solutions below