简体   繁体   中英

How to pass a map between two processes in linux?

Suppose I have a father process p1 and its child process p2 . p1 creates p2 and lets p 2 do something then stores the result into a std::map . Now p1 wants to access the map.

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. The type of the map is <std::string, double> , but I am not sure how to dump it to a char array.

  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 ? 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. 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

We didn't use std::map or boost::unordered_map in shared memory since it's not easy to maintain and debug. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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