14

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

Is there a better way?

marathon
  • 7,881
  • 17
  • 74
  • 137

2 Answers2

5

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

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.

MFT
  • 76
  • 2
  • 5
1

If you are working with shared_memory_objects:

  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);
    }
  }
Luca Fagioli
  • 12,722
  • 5
  • 59
  • 57