ubuntu - pcntl 子进程引用并修改父进程数据的问题??
怪我咯
怪我咯 2017-04-24 09:12:06
0
3
781

代码:

$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(),没有发生任何变化!
                    // 子进程无法修改主进程中的数据。
                    // 子进程中该如何修改主进程中的数据,实现数据共享??
}

结果:

进程间该如何进行数据交流??

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(3)
大家讲道理

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.

PHPzhong

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.

// 创建key和消息队列
$msg_key = ftok(__FILE__, 'a');
$msg_queue = msg_get_queue($msg_key);

$data = array();
$p = pcntl_fork();

if ($p === -1) {
    exit('创建进程失败!' . PHP_EOL);
} else if ($p === 0) {
    // 修改主进程中的数据
    // 将修改的数据发送到消息队列
    msg_send($msg_queue, 1, array('cxl' , 'ys'));
    exit();
} else {
    pcntl_wait($status);
    
    // 子进程返回后,查看数据变动
    // 接收队列中的数据
    msg_receive($msg_queue, 1, $msg_type, 1024, $msg);
    // 销毁队列
    msg_remove_queue($msg_queue);
    
    $data = $msg;
    print_r($data); 
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template