Create a shared-memory vector of strings

前端 未结 3 1646
我寻月下人不归
我寻月下人不归 2020-12-16 03:23

I am trying to create a class managing a shared-memory vector of (std)strings.

typedef boost::interprocess::allocator

        
3条回答
  •  感动是毒
    2020-12-16 04:00

    You can use boost::interprocess::managed_shared_memory. The following program passes a boost::interprocess::string between 2 processes. Works fine on my machine (Ubuntu Linux). You can use managed_shared_memory to pass vectors or objects. boost::interprocess::string has a c_str() method.

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main(int argc, char *argv[])
    {
      using namespace boost::interprocess;
      typedef boost::interprocess::allocator CharAllocator;
      typedef boost::interprocess::basic_string, CharAllocator> string;
      if(argc == 1){  //Parent process
    
          boost::interprocess::shared_memory_object::remove("MySharedMemory");
    
          //Create a shared memory object.
          managed_shared_memory shm (create_only, "MySharedMemory", 1024);
    
          string *s = shm.find_or_construct("String")("Hello!", shm.get_segment_manager());
          std::cout << *s << std::endl;
    
          //Launch child process
          std::string s1(argv[0]); s1 += " child ";
          if(0 != std::system(s1.c_str()))
             return 1;
      }
      else{
          //Open already created shared memory object.
          managed_shared_memory shm (open_only, "MySharedMemory");
          std::pair ret = shm.find("String");
          std::cout << *(ret.first) << std::endl;
      }
      return 0;
    }
    

提交回复
热议问题