I wanna share a pointer of map during 2 processes. So I tried mmap. I tested mmap in a single process. Here is my code:
#include <vector>
#include <iostream>
#include <sys/mman.h>
#include <unistd.h>
#include <cstdlib>
#include <stdio.h>
#include <map>
using namespace std;
int main(int argc, char *argv[])
{
map<string,string> a, *b;
b = (map<string,string> *)mmap(&a,sizeof(map<string,string>),
PROT_READ|PROT_WRITE,MAP_ANON|MAP_SHARED,-1,0);
b->insert(map<string,string>::value_type("a","b")); //error
cout << b->size() << endl;
}
when it runs to b->insert(), Segmentation fault occured. If I remove b->insert(), there is no error (still have b->size). What’s the problem with my code?
You are allocating new memory with
mmap(why? seems like a bad idea…) but you are not initializing yourmap. Use “placement new” to initialize it.But I suspect something is terribly wrong, and
mmapreally shouldn’t be involved here…Edit: From the comments, it sounds like you want to share memory between two processes. Shared memory is probably far beyond your current skill level. You cannot normally place a
std::mapobject inside a shared memory segment, because it will contain references to internal objects on the heap, which will not be shared, unless you can create a custom allocator to only create subobjects inside the shared memory segment.You can create a shared memory object with
shm_open, you can change its size withftruncate, and you can map it into memory withmmap. Different processes thatshm_openthe same name will get the same object, and the shared object descriptor can also be passed between processes just like file descriptors.