Question

I have passed hours and days to find why php share the memory between my forked children and I figured that if the parent set a var in a function before forking then the function will always return the same result in the children :~

new mytest;
class mytest{
    var $t = 'Parent';
    public function __construct(){              
        //$this->runChildProcess($i);       

        $pidsCount = 0;
        for($i = 0; $i < 5; $i++) { 
            $pids[$pidsCount] = pcntl_fork();
            if($pids[$pidsCount]) {
                $this->t = 'Parent';
                // i am the parent
                $pidsCount++;
            }
            else {
                $this->t = 'Enfant';
                // i am the child
                $this->runChildProcess($i);
                exit();
            }
        }
        for($i = 0; $i < $pidsCount; $i++) {
            pcntl_waitpid($pids[$i], $status, WUNTRACED);
        }
    }

    function runChildProcess($i) {
        $a = rand(0,100)."\n";
        echo $this->t.' : '.$a;
    }   
}

If you run this sample it'll be just fine, the children will output different numbers. But if you un-comment the first $this->runChildProcess($i); then you'll see that all the children will return the same result (the first one calculated by a children)

I don't know how to deal with that :(

Was it helpful?

Solution

I don't think this is anything to do with memory sharing. You're just seeing the behaviour of rand.

With that line commented out, each child calls rand for the first time, so each gets seeded independently.

With that line uncommented, then rand is seeded before any of the children are forked. So they all see the same seed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top