mar*_*hon 7 c++ boost shared-memory
我能看到如何做到这一点的唯一方法是尝试访问它并捕获抛出的异常(如果它不存在).
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;
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
小智 5
我正在玩 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 ...> */
Run Code Online (Sandbox Code Playgroud)
以上内容来自 Managed_open_or_create_impl.hpp 中的 priv_open_or_create() 方法中的第 360 行左右。看来答案是否定的。不,在尝试打开共享内存之前没有好的方法来检查它是否已创建。
| 归档时间: |
|
| 查看次数: |
1233 次 |
| 最近记录: |