【问题标题】:Is there a better way to check for the existence of a boost shared memory segment?有没有更好的方法来检查是否存在 boost 共享内存段?
【发布时间】:2014-10-23 19:50:53
【问题描述】:

我知道如何做到这一点的唯一方法是尝试访问它并捕获如果不存在则抛出的异常。

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;
}

有没有更好的办法?

【问题讨论】:

    标签: c++ boost shared-memory


    【解决方案1】:

    我正在玩 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 大约第 360 行,在 priv_open_or_create() 方法中。似乎答案是否定的。不,没有好方法可以在尝试打开共享内存之前检查它是否已创建。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-25
      • 2022-09-23
      • 2022-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 2018-05-11
      相关资源
      最近更新 更多