首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何解决Boost错误:在抛出'boost::interprocess::interprocess_exception‘实例后终止调用

如何解决Boost错误:在抛出'boost::interprocess::interprocess_exception‘实例后终止调用
EN

Stack Overflow用户
提问于 2022-09-07 12:01:36
回答 1查看 125关注 0票数 1

我正在尝试使用Boost来创建共享内存。这是我的密码:

代码语言:javascript
复制
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>

#define BUF_SIZE            1*1024*1024

int main()
{
    shared_memory_object tx_data_buffer(create_only ,"tx_data_memory", read_write);
    tx_data_buffer.truncate(BUF_SIZE);
    mapped_region tx_region(tx_data_buffer, read_write);

    //Get the address of the region
    cout << "\n\nTX Data Buffer Virtual Address = " << tx_region.get_address() << endl;

    //Get the size of the region
    cout << "\n\nTX Data Buffer Size = " << tx1_region.get_size() << endl;
}

我之前成功地运行了上述代码几次(不确定是一次还是多次)。但是,当我再次尝试运行相同的代码时,它会给出以下错误:

代码语言:javascript
复制
terminate called after throwing an instance of 'boost::interprocess::interprocess_exception'
  what():  File exists

我正在Linux中的Eclipse上运行代码。知道是什么导致了这一切吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-07 12:38:19

您特别要求shared_memory_object以create_only模式打开。当然,当它存在时,它不能被创建,所以它失败了。错误信息非常清楚:“文件存在”。

解决问题的一种方法是使用open_or_create来代替:

代码语言:javascript
复制
namespace bip = boost::interprocess;

bip::shared_memory_object tx_data_buffer(bip::open_or_create ,"tx_data_memory", bip::read_write);

或者,或者显式删除共享内存对象:

代码语言:javascript
复制
bip::shared_memory_object::remove("tx_data_buffer");
bip::shared_memory_object tx_data_buffer(bip::create_only, "tx_data_memory",
                                         bip::read_write);

请记住,您可以同步访问来自不同线程的共享内存。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73635160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档