Search code examples
phpforkpcntl

PHP pcntl Variable Scope


I want to be able to modify array elements that are in the parent pid. Here is some example code:

$arrayContainer = array(
    array(
          "id" => 1,
          "name" => "Lenny"
    ),
    array(
          "id" => 2,
          "name" => "Dudley"
    ),
    array(
          "id" => 3,
          "name" => "Simon"
    ),
);

foreach ($arrayContainer as $key => $element) {
    $pid = pcntl_fork();
    if($pid == -1) {
        // Something went wrong (handle errors here)
        die("Could not fork!");
    } elseif($pid == 0) {
        $arrayContainer[$key]['size'] = 123;
        $arrayContainer[$key]['fileName'] = 'somefile.txt';
        // The child dies after a short while, becoming a zombie
        exit();  
    } else {
        // This part is only executed in the parent
    }
}

So when this script ends the two elements i wrote in the child process are not there at the end of the foreach loop. I can't modify the array that is in the parent pid from the child. I understand why but can't think of a nice solution that will allow me to. Can you suggest anything? Globals or something?


Solution

  • The parent/children processes will be sharing the same stdin/stdout. If the PARENT process remaps its stdin/stdout before each fork() call, you can have dedicated stdins/stdouts for each child. This would let you speak to each child using its own communications channel, and also listen to each child individually.

    Then it's just a simple matter of coming up with a simple communications protocol to let children pass modified data back to the parent.