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 => $eleme开发者_StackOverflow社区nt) {
$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?
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.
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
精彩评论