I'm using boost::interprocess to share objects between processes. I have two files, a "server.cpp" that generates a struct object and passes the object into a map with an int index; and a "client.cpp" file that retrieves the memory data and iterates through the data, outputting to console.
The struct looks like this:
struct mydata o {
string MY_STRING;
int MY_INT;
};
And the object:
mydata o;
o.MY_STRING = "hello";
o.MY_INT = 45;
Both server and client compile correctly. But for some reason the client executable throws a segmentation fault if I try to access a string rather than a float or an integer in the client. For example the below second.MY_INT will cout to console, but second.MY_STRING throws this error when running.
#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>
#include <string>
#include "objects.cpp" //definitions for objects
using std::string;
using namespace boost::interprocess;
int main ()
{
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 order MappedType;
typedef std::pair<const int, order> 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;
std::cout<<iter->first<<" "<<iter->second.MYINT<<" "<<iter->second.MYSTRING<<"\n";
}
}catch(std::exception &e)
{
std::cout<<" error " << e.what() <<std::endl;
shared_memory_object::remove("SharedMemoryName");
}
return 0;
}
the error when running:
Segmentation fault (core dumped)
I'm pretty sure the server is passing the entire object to memory, and the client can retrieve it (as i can access some of the objects attributes), and that its just a formatting issue.