如何解决Boost共享内存创建时的interprocess_exception异常
Boost共享内存创建报错“File exists”原因及解决方法
问题描述
使用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); // 获取区域地址 std::cout << "\n\nTX Data Buffer Virtual Address = " << tx_region.get_address() << std::endl; // 获取区域大小(注:原代码此处变量名错误,应为tx_region而非tx1_region) std::cout << "\n\nTX Data Buffer Size = " << tx_region.get_size() << std::endl; }
此前代码曾成功运行多次,但当前运行时抛出如下异常:
terminate called after throwing an instance of 'boost::interprocess::interprocess_exception' what(): File exists
运行环境为Linux系统下的Eclipse。
报错原因
这个异常的核心原因是系统中已经存在名为tx_data_memory的共享内存对象。
你代码中使用的create_only标志,要求Boost创建一个全新的共享内存对象——如果同名对象已经存在,就会直接抛出“File exists”异常。导致对象残留的常见场景:
- 之前运行的程序异常崩溃,没有执行共享内存的清理逻辑;
- 其他进程创建了同名的共享内存对象且未销毁。
另外注意:原代码最后输出大小的语句中,错误使用了未定义的tx1_region,这会导致编译或运行错误,需要修正为tx_region。
解决方法
1. 手动清理残留的共享内存对象
在Linux终端执行命令查看系统中所有共享内存:
ipcs -m
在输出结果中找到与tx_data_memory对应的条目(可通过键值或创建者PID关联),然后用ipcrm命令删除:
ipcrm -m <shmid>
将<shmid>替换为ipcs输出中对应条目的ID值。
2. 修改代码适配已存在的对象
如果希望程序在共享内存对象已存在时直接复用,而非抛出异常,可将create_only替换为open_or_create标志:
shared_memory_object tx_data_buffer(boost::interprocess::open_or_create, "tx_data_memory", boost::interprocess::read_write);
(注:建议显式写出Boost命名空间,避免编译错误)
3. 程序退出时自动清理共享内存
在程序正常退出路径中添加清理逻辑,比如在main函数末尾加入:
boost::interprocess::shared_memory_object::remove("tx_data_memory");
注意:如果程序异常崩溃,该清理逻辑不会执行,因此仍需配合open_or_create或手动清理的方式处理极端情况。
内容的提问来源于stack exchange,提问作者Mobi Zaman
相关产品推荐
相关产品推荐

