我能看到如何做到这一点的唯一方法是尝试访问它并捕获如果它不存在则抛出的异常。
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;
}
有更好的方法吗?
答案 0 :(得分:2)
我正在玩boost :: interprocess并碰巧问了同样的问题。在我最终确定open_or_create以满足我的需求之前,我做了一点挖掘。然而,在模板意大利面的深处是提升(我的是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 ...> */
以上是来自于大约360行的managed_open_or_create_impl.hpp,在priv_open_or_create()方法中。似乎答案是否定的。不,在尝试打开共享内存之前,没有好办法检查是否已创建共享内存。