1

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?

hakre
  • 193,403
  • 52
  • 435
  • 836
gprime
  • 2,283
  • 7
  • 38
  • 50

2 Answers2

3

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.

Marc B
  • 356,200
  • 43
  • 426
  • 500
3

you should try using a shared memory: http://www.php.net/manual/en/ref.shmop.php

having a well known name for a shared memory will let you shmop_open() in the parent and the children as needed. beware, you should use a semaphore to protect this shared memory so no two writes occur at the same time. that is, have a mutual exclusive lock on the shared memory

marcelog
  • 7,062
  • 1
  • 33
  • 46
  • Yeah, I am actually refactoring it right now using memcached. Just have to change a lot of my logic but the result is going to be good. – gprime Jul 26 '11 at 20:57