2013-01-18 26 views
0

我已经过了几个小时和几天找到为什么php分享我分叉的孩子和我之间的内存计算过,如果父母中一个函数分叉之前设置一个变量,然后该函数将始终返回〜PHP的分叉和内存共享我发疯

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

如果你运行这个示例它会很好,孩子们会输出不同的数字。 但是,如果你取消注释第一$this->runChildProcess($i);然后你会看到所有的孩子将返回相同的结果(由儿童计算的第一个)

我不知道如何处理是: (

回答

1

我不认为这是什么做的内存共享。你只是看到的rand行为。

随着该行注释掉,每个孩子要求rand首次,所以每个独立获得种子

随着该行注释掉,然后rand是之前接种任何儿童被分叉。因此,他们都看到了相同的种子。

+0

该死的奥利你说得对!谢谢 – beunwa