有没有更好的方法来检查boost共享内存段的存在

Is there a better way to check for the existence of a boost shared memory segment?

本文关键字:共享 内存 boost 存在 检查 更好 方法 有没有      更新时间:2023-10-16

我能看到如何做到这一点的唯一方法是尝试访问它,并捕获如果不存在就会抛出的异常。

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)的深处,我们发现了这个宝石:

      /*<... 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行,在priva_open_or_create()方法中。答案似乎是否定的。不,在尝试打开共享内存之前,没有很好的方法来检查是否已经创建了共享内存。

如果使用shared_memory_object s:

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