我想在2个进程中共享一个map的指针。所以我尝试了mmap。我在一个进程中测试了mmap。这里是我的代码:mmap后出现分割错误()
#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;
}
当它运行到
b->insert()
,分割故障发生。如果我删除b->insert()
,则没有错误(仍然有b->size
)。我的代码有什么问题?
即使您将能够使用在mmap中分配的映射,它也不能在进程之间共享。 STL并不存储b中的所有元素,它使用通过new/delete或malloc/free工作的指针和经典分配器。如果你真的需要共享一些数据结构,你需要自己定义和实现它。 – osgx 2011-05-22 10:22:34