我正在尝试创建一个管理(std)字符串的共享内存向量的类。
typedef boost::interprocess::allocator<std::string, boost::interprocess::managed_shared_memory::segment_manager> shmem_allocator;
typedef boost::interprocess::vector<std::string, shmem_allocator> shmem_vector;
shmem_mgr::shmem_mgr() :
shmem_(create_only, SHMEM_KEY, SHMEM_SIZE),
allocator_(shmem_.get_segment_manager())
{
mutex_ = shmem_.find_or_construct<interprocess_mutex>(SHMEM_MUTEX)();
condition_ = shmem_.find_or_construct<interprocess_condition>(SHMEM_CONDITION)();
//buffer_ is of type shmem_vector
buffer_ = shmem_.construct<shmem_vector>(SHMEM_BUFFER_KEY)(allocator_);
}
void shmem_mgr::run() {
running_ = true;
while(running_) {
scoped_lock<interprocess_mutex> lock ( *mutex_ );
int size = buffer_->size();
log_.debug() << size << " queued request(s) found" << std::endl; //LINE 27
for(int i=0; i<size; i++) {
log_.debug() << buffer_->at(i); // at() crashes my app
}
buffer_->clear(); //so does clear()
condition_->wait (lock);
}
}
客户端成功将一个字符串添加到向量中(它也成功地从缓冲区中读取该字符串进行调试),管理器(上面的代码)接收到信号(条件变量),写入向量中有一个字符串(第 27 行),但是当它试图通过at()
应用程序获取该字符串时会崩溃。
编辑:我已经想通了,使用
std::string
是不可能的,string
boost ipc 中有一个容器专门用于这种情况。这并没有改变我需要一个 (boost/std) 字符串向量的事实......
问:如何跨共享内存传递字符串?我需要将它们存储在 shmem 中的某个缓冲区(一次能够存储 >1 个)中,然后在第二个进程中获取 - 这就是要求。输入总是std::string
如此,输出也是,但 shmem 中的内部表示可能不同。