这是我为学习共享内存中映射的使用而编写的最近的示例。它编译得如此可能,您可以尝试使用它来满足您的要求。
创建共享内存并将映射放入其中的服务器进程的代码:-
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <functional>
#include <utility>
int main ()
{
using namespace boost::interprocess;
// remove earlier existing SHM
shared_memory_object::remove("SharedMemoryName");
// create new
managed_shared_memory segment(create_only,"SharedMemoryName",65536);
//Note that map<Key, MappedType>'s value_type is std::pair<const Key, MappedType>,
//so the allocator must allocate that pair.
typedef int KeyType;
typedef float MappedType;
typedef std::pair<const int, float> ValueType;
//allocator of for the map.
typedef allocator<ValueType, managed_shared_memory::segment_manager> ShmemAllocator;
//third parameter argument is the ordering function is used to compare the keys.
typedef map<KeyType, MappedType, std::less<KeyType>, ShmemAllocator> MySHMMap;
//Initialize the shared memory STL-compatible allocator
ShmemAllocator alloc_inst (segment.get_segment_manager());
// offset ptr within SHM for map
offset_ptr<MySHMMap> m_pmap = segment.construct<MySHMMap>("MySHMMapName")(std::less<int>(), alloc_inst);
//Insert data in the map
for(int i = 0; i < 10; ++i)
{
m_pmap->insert(std::pair<const int, float>(i, (float)i));
}
return 0;
}
附加到内存并访问映射数据的客户端进程的代码。
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/map.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <functional>
#include <utility>
#include <iostream>
int main ()
{
using namespace boost::interprocess;
try
{
managed_shared_memory segment(open_or_create, "SharedMemoryName",65536);
//Again the map<Key, MappedType>'s value_type is std::pair<const Key, MappedType>, so the allocator must allocate that pair.
typedef int KeyType;
typedef float MappedType;
typedef std::pair<const int, float> ValueType;
//Assign allocator
typedef allocator<ValueType, managed_shared_memory::segment_manager> ShmemAllocator;
//The map
typedef map<KeyType, MappedType, std::less<KeyType>, ShmemAllocator> MySHMMap;
//Initialize the shared memory STL-compatible allocator
ShmemAllocator alloc_inst (segment.get_segment_manager());
//access the map in SHM through the offset ptr
MySHMMap :: iterator iter;
offset_ptr<MySHMMap> m_pmap = segment.find<MySHMMap>("MySHMMapName").first;
iter=m_pmap->begin();
for(; iter!=m_pmap->end();iter++)
{
std::cout<<"\n "<<iter->first<<" "<<iter->second;
}
}catch(std::exception &e)
{
std::cout<<" error " << e.what() <<std::endl;
shared_memory_object::remove("SharedMemoryName");
}
return 0;
}
客户端进程的代码解释了如何使用“名称”和偏移指针,其他进程可以附加和访问服务器进程在 SHM 中创建的 Map 内容。但是,在创建新的共享内存段时分配大小(此处为“65536”),我不确定是否可以缩小大小,尽管您可能可以创建更多的共享内存块来扩展 SHM ...
希望它有所帮助...