我正在嘗試使用 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 上運行代碼。知道是什么原因造成的嗎?
uj5u.com熱心網友回復:
您特別要求 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://www.uj5u.com/shujuku/505644.html
