设置共享内存时的分段错误

时间:2012-04-14 07:01:59

标签: c++ boost

我一遍又一遍地摸不着头脑,但却想不出原因。基本上代码编译但是当我运行程序时,我遇到了分段错误。我尝试打印一些像它工作的大小的东西。似乎分割来自共享内存的处理。我需要一些帮助...

#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/set.hpp>
//#include <set>
#include <string>
#include <cstdlib> //std::system
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace boost::interprocess;

//Main function. For parent process argc == 1, for child process argc == 2
int main(int argc, char **argv)
{
   if(argc == 1) { //Parent process
   //Remove shared memory on construction and destruction
     struct shm_remove
     {
       shm_remove() { shared_memory_object::remove("MySharedMemory"); }
       ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
     } remover;

     //Create a new segment with given name and size
     managed_shared_memory segment(create_only, "MySharedMemory", 65536);

     //Construct a set named "MySet" in shared memory
     set<int> *myset = segment.construct<set<int> >("MySet")();

     for(int i = 1; i < 4; ++i)  //Insert data in the set
       myset->insert(i);

     std::cout << "Printing from parent process:" << std::endl;
     std::copy(myset->begin(), myset->end(), std::ostream_iterator<int>(std::cout, ", "));
     std::cout << std::endl;

     //Launch child process
     std::string s(argv[0]); 
     s += " child ";
     if(0 != std::system(s.c_str()))
       return 1;

     //Check child has destroyed the set
     if(segment.find<set<int> >("MySet").first)
       return 1;
   }
   else { //Child process
     //Open the managed segment
     managed_shared_memory segment(open_only, "MySharedMemory");

     //Find the set using the c-string name
     set<int> *myset = segment.find<set<int> >("MySet").first;

     std::cout << "Printing from child process:" << std::endl;
     std::cout << "Size is " << myset->size() << std::endl;
     std::copy(myset->begin(), myset->end(), std::ostream_iterator<int>(std::cout, ", "));
     std::cout << std::endl;

     //When done, destroy the set from the segment
     segment.destroy<set<int> >("MySet");
   }

   return 0;
};

0 个答案:

没有答案