1

Suppose I have a father process p1 and its child process p2. p1 creates p2 and lets p2 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.

thor
  • 21,418
  • 31
  • 87
  • 173
Dingbao Xie
  • 716
  • 9
  • 21
  • Do you need a one-time copy from p2 to p1 or will there be an ongoing need to share the data -- the answer may inform your choice of solution. – John Hascall May 28 '15 at 23:21
  • BTW, In your first alternative what you are looking for is called marshaling/un-marshaling. One possible approach is to just print into the array, for example, `snprintf(shmbuffer, sizeof(shmbuffer), "%s %f\n", StrVar, DbleVar);` More sophisticated/complicated approaches are certainly possible. – John Hascall May 28 '15 at 23:25
  • I just need one time copy, because p2 will exit after execution. Then p1 will create another child process p3 and repeat the process. – Dingbao Xie May 28 '15 at 23:25
  • I'm thinking the first approach, then. – John Hascall May 28 '15 at 23:26
  • The second one does not seem correct? – Dingbao Xie May 28 '15 at 23:27
  • It just seems like more work. – John Hascall May 28 '15 at 23:27
  • Passing non-POD objects can be a problem. `std::map` may not be binary compatible between the two programs (and let me tell you; that bug is great fun to debug for the first time.) – Ed S. May 28 '15 at 23:46

1 Answers1

2

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.

Community
  • 1
  • 1
Tim3880
  • 2,563
  • 1
  • 11
  • 14