有没有更好的方法来检查是否存在Boost共享内存段? [英] Is there a better way to check for the existence of a boost shared memory segment?

查看:56
本文介绍了有没有更好的方法来检查是否存在Boost共享内存段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能看到的唯一方法是尝试访问它,并捕获不存在的异常.

The only way I could see how to do this was to try to access it and catch the exception that gets thrown if it isn't there.

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之前,我做了一些挖掘工作.然而,在通心粉意粉的肠子深处(我的是1.62),我们发现了这个宝石:

I was playing around with boost::interprocess and happened to ask the same question. I did a little digging before finally settling on open_or_create for my needs. However, deep in the bowels of the template spaghetti that is boost (mine is 1.62), we find this gem:

      /*<... 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 ...> */

以上内容来自priv_open_or_create()方法中的managed_open_or_create_impl.hpp,大约在第360行.似乎答案是否定的.不,没有一种好的方法可以在尝试打开共享内存之前检查它是否已创建.

The above is from managed_open_or_create_impl.hpp at about line 360, in the priv_open_or_create() method. Seems the answer is no. No, there's no good way to check whether a shared memory has been created prior to trying to opening it.

这篇关于有没有更好的方法来检查是否存在Boost共享内存段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆