简体   繁体   English

如何在Linux中的两个进程之间传递映射?

[英]How to pass a map between two processes in linux?

Suppose I have a father process p1 and its child process p2 . 假设我有一个父进程p1及其子进程p2 p1 creates p2 and lets p 2 do something then stores the result into a std::map . p1创建p2并让p 2做一些事情,然后将结果存储到std::map Now p1 wants to access the map. 现在, p1要访问地图。

This is inter-process communication, I want to use shared memory to do that. 这是进程间通信,我想使用共享内存来做到这一点。 I'm thinking of two solutions. 我正在考虑两种解决方案。

  1. p2 dumps the map to a char array and writes it to the shared memory and then p1 reads the shared memory to reconstruct the map. p2将映射转储到char数组,并将其写入共享内存,然后p1读取共享内存以重建映射。 The type of the map is <std::string, double> , but I am not sure how to dump it to a char array. 映射的类型是<std::string, double> ,但是我不确定如何将其转储到char数组。

  2. In p2, suppose the pointer to the shared memory is void *shm , can I allocate the memory of the map using this way std::map<std::string, double>* result = (std::map<std::string, double>*)shm and then insert elements to result ? 在p2中,假设共享内存的指针为void *shm ,我可以使用这种方式分配映射的内存std::map<std::string, double>* result = (std::map<std::string, double>*)shm ,然后插入元素以生成result In p1, I can do the same thing std::map<std::string, double>* result = (std::map<std::string, double>*)shm and then iterate the map. 在p1中,我可以做同样的事情std::map<std::string, double>* result = (std::map<std::string, double>*)shm然后迭代地图。 But I am not sure whether it is correct. 但我不确定这是否正确。

I asked a similar question not long ago: 我不久前问了一个类似的问题:

boost unordered map in shared memory using std::string key 使用std :: string键增强共享内存中的无序映射

We didn't use std::map or boost::unordered_map in shared memory since it's not easy to maintain and debug. 我们没有在共享内存中使用std :: map或boost :: unordered_map,因为它不容易维护和调试。 We build our own hash table in boost shared memory (basically an array on the shared memory) and it works fine. 我们在增强型共享内存(基本上是共享内存中的数组)中构建自己的哈希表,并且工作正常。

In you case, you can dump the map to the memory just like writing to a binary file. 在这种情况下,您可以将映射转储到内存中,就像写入二进制文件一样。 The second process reads it from the shared memory and rebuild the map. 第二个过程从共享内存中读取它并重建映射。

If your key is not very long, you can dump the map as an array of fixed size structure into the shared memory, which is very easy to write and read. 如果密钥不是很长,则可以将地图作为固定大小结构的数组转储到共享内存中,这非常容易读写。

Your second approach may not work. 您的第二种方法可能行不通。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM