我正在尝试使用Boost来创建共享内存。这是我的密码:
#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上运行代码。知道是什么导致了这一切吗?
发布于 2022-09-07 12:38:19
您特别要求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);或者,或者显式删除共享内存对象:
bip::shared_memory_object::remove("tx_data_buffer");
bip::shared_memory_object tx_data_buffer(bip::create_only, "tx_data_memory",
bip::read_write);请记住,您可以同步访问来自不同线程的共享内存。
https://stackoverflow.com/questions/73635160
复制相似问题