繁体   English   中英

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

[英]How to solve Boost Error: terminate called after throwing an instance of 'boost::interprocess::interprocess_exception'

我正在尝试使用 Boost 创建共享 memory。 这是我的代码:

#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;
}

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

terminate called after throwing an instance of 'boost::interprocess::interprocess_exception'
  what():  File exists

我正在 Linux 中的 Eclipse 上运行代码。 知道是什么原因造成的吗?

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

解决问题的一种方法是改用open_or_create

namespace bip = boost::interprocess;

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

或者,或者,显式删除共享的 memory object:

bip::shared_memory_object::remove("tx_data_buffer");
bip::shared_memory_object tx_data_buffer(bip::create_only, "tx_data_memory",
                                         bip::read_write);

请记住,您可以从不同的线程同步访问共享的 memory。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM