Segmentation fault after mmap()
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 <vect开发者_如何学Pythonor>
#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?
Despite its name, mmap()
has nothing to do with std::map
. When you use mmap()
, you get access to a raw block of memory with no structure. You cannot directly store STL objects like std::map
in that block, because there are internal pointers inside the STL objects that are not compatible with mmap()
.
When you use mmap()
to map the same block of memory into two different processes, that block may not even appear at the same address in memory. You must take this into account when defining the format of data you will store in the shared memory.
You are allocating new memory with mmap
(why? seems like a bad idea...) but you are not initializing your map
. Use "placement new" to initialize it.
void *p = mmap(....);
if (p == MAP_FAILED)
abort();
map<string,string> *b = new(p) map<string,string>();
b->insert(...);
But I suspect something is terribly wrong, and mmap
really 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::map
object 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 with ftruncate
, and you can map it into memory with mmap
. Different processes that shm_open
the same name will get the same object, and the shared object descriptor can also be passed between processes just like file descriptors.
精彩评论