Search code examples
phpforkpcntl

Why does pcntl_fork() copy PHP objects?


The manual for pcntl_fork() says:

The pcntl_fork() function creates a child process that differs from the parent process only in its PID and PPID.

However, running this simple test surprised me:

class Foo
{
    public function bar()
    {
        if (pcntl_fork()) {
            echo spl_object_hash($this), PHP_EOL;
        } else {
            echo spl_object_hash($this), PHP_EOL;
        }
    }
}

(new Foo)->bar();

The result looks like:

000000005ec7fd31000000003f0fcfe6
000000006b4cd5fc000000007fee8ab7

From what the documentation says, I would have expected the parent and the child to share the same variables, and in particular, when fork()ed from within an object, I would have expected the reference to the object to be the same in both processes. But the example above shows they're not.

Interesting to note, there is no cloning happening here, it looks like the object is just copied. If I add a __clone() function, I can see it's not called during the forking.

Any reason why the variables/objects are not shared by both processes, or any good reading on the subject folks?


Solution

  • The object hash will not being calculated when the object is created (as one could think). The object hash will be calculated when spl_object_hash() is called the first time for the object. This is after fork in your example.

    Further note that for the calculation of the hash some randomness is used, therefore the different hashes.