代码:
$data = array();
$p = pcntl_fork();
if ($p === -1) {
exit('创建进程失败!' . PHP_EOL);
} else if ($p === 0) {
// 修改主进程中的数据
$data = array('cxl' , 'ys');
} else {
pcntl_wait($status);
// 子进程返回后,查看数据变动
print_r($data); // 结果 array(),没有发生任何变化!
// 子进程无法修改主进程中的数据。
// 子进程中该如何修改主进程中的数据,实现数据共享??
}
结果:
进程间该如何进行数据交流??
After the child process is created, it has been decoupled from the variable data of the parent process. If you want the child process to modify the parent process variables, you need to implement inter-process communication and implement the relevant code yourself. Of course, variables can also be shared through shared memory.
There are many methods available for inter-process communication. The most common, TCP.
I just happened to be learning pcntl, and I also thought about inter-process communication. One of the available methods I found was using message queues. I thought it was not too complicated, so I added a few sentences to your code. You can try it and help each other.