我能看到如何做到这一点的唯一方法是尝试访问它并捕获如果它不存在则抛出的异常。
bool exists()
{
using namespace boost::interprocess;
try
{
managed_shared_memory segment(open_only, kSharedMemorySegmentName);
return segment.check_sanity();
}
catch (const std::exception &ex) {
std::cout << "managed_shared_memory ex: " << ex.what();
}
return false;
}
有更好的方法吗?
我正在玩 boost::interprocess 并碰巧问了同样的问题。在最终根据我的需要选择 open_or_create 之前,我做了一些挖掘。然而,在 boost 意大利面条模板的深处(我的是 1.62),我们发现了这个宝石:
/*<... snip ...>*/
//This loop is very ugly, but brute force is sometimes better
//than diplomacy. If someone knows how to open or create a
//file and know if we have really created it or just open it
//drop me a e-mail!
bool completed = false;
spin_wait swait;
while(!completed){
try{
create_device<FileBased>(dev, id, size, perm, file_like_t());
created = true;
completed = true;
}
catch(interprocess_exception &ex){
if(ex.get_error_code() != already_exists_error){
throw;
}
else{
try{
DeviceAbstraction tmp(open_only, id, read_write);
dev.swap(tmp);
created = false;
completed = true;
}
catch(interprocess_exception &e){
if(e.get_error_code() != not_found_error){
throw;
}
}
catch(...){
throw;
}
}
}
catch(...){
throw;
}
swait.yield();
}
/* <... snip ...> */
以上内容来自 Managed_open_or_create_impl.hpp 中的 priv_open_or_create() 方法中的第 360 行左右。看来答案是否定的。不,在尝试打开共享内存之前没有好的方法来检查它是否已创建。
如果您正在与
shared_memory_object
合作:
using namespace boost::interprocess;
bool exists()
{
try
{
shared_memory_object shm_source(open_only, map_shared_memory_name.c_str(), read_only);
std::string name = shm_source.get_name();
return (!name.empty());
}
catch (const std::exception &ex)
{
return (false);
}
}
这个怎么样?
if (shared_memory_object::remove("MySharedMemory"))
{
std::cout << "Removing Shm::" << "MySharedMemory"<< std::endl;
}
return m_pSegment->check_sanity();