I have a very small example of two programs, one to write a shared memory segment and another to read from it. I realise there are potentially issues with std::string
(and other containers) so have tried boost::interprocess::string
which is a boost::containers::string
. I am pretty sure this is missing something really fundamental and simple, but cannot see it!
In any case the synopsis is that when the string is small (I think though larger than SSO) running the first program writes the memory and the second reads perfectly well. If, however, I make the string pretty large as in the example here then the read program segfaults. I have success with this if both read and write are in the same process, but different functions (so not sharing any data except via ipc. Code below writeipc.cc
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <iostream>
#include <utility>
int main()
{
typedef boost::interprocess::string bi_string;
boost::interprocess::shared_memory_object::remove("Test");
boost::interprocess::managed_shared_memory managed_shm(boost::interprocess::create_only, "Test", 65536);
bi_string* i = managed_shm.construct<bi_string>("string")("abcdefghijklmnopqrstuvwxyzaskl;dfjaskldfjasldfjasdl;fkjwrotijuergonmdlkfsvmljjjjjjjjjjjjjj"); // make smaller (ie "jjjjjjjjjjjjjj" and test passes
std::cout << "inserting into shm" << *i << std::endl;
std::pair<bi_string*, size_t> q = managed_shm.find<bi_string>("string");
std::cout << *q.first << std::endl;
while(true)
std::cout << "still running"; // hack to keep process running (not required)
}
readipc.cc
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <iostream>
int main()
{
typedef boost::interprocess::string bi_string;
boost::interprocess::managed_shared_memory managed_shm(boost::interprocess::open_only, "Test");
std::pair<bi_string*, std::size_t> p = managed_shm.find<bi_string>("string");
std::cout << "existing value" << *p.first << std::endl;
}