我有两个程序的一个非常小的示例,一个用于写入共享内存段,另一个用于从中读取。我意识到(和其他容器)存在潜在问题,std::string
因此尝试boost::interprocess::string
了哪个是boost::containers::string
. 我很确定这缺少一些非常基本和简单的东西,但看不到它!
无论如何,概要是当字符串很小(我认为虽然比 SSO 大)时,运行第一个程序会写入内存,而第二个程序读取得非常好。但是,如果我像这里的示例那样使字符串非常大,则读取程序会出现段错误。如果读取和写入都在同一个进程中,但功能不同(因此除了通过 ipc 之外不共享任何数据。代码如下 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;
}