Home  >  Q&A  >  body text

ubuntu - pcntl 子进程引用并修改父进程数据的问题??

代码:

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

结果:

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

怪我咯怪我咯2734 days ago748

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-04-24 09:14:06

    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.

    reply
    0
  • PHPz

    PHPz2017-04-24 09:14:06

    There are many methods available for inter-process communication. The most common, TCP.

    reply
    0
  • 迷茫

    迷茫2017-04-24 09:14:06

    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); 
    }

    reply
    0
  • Cancelreply