Boost logo

Boost Users :

From: Henry (dimensiondude.oss_at_[hidden])
Date: 2008-06-11 01:27:22


I am trying to use a vector with a managed_mapped_file. http://www.boost.org/doc/libs/1_35_0/doc/html/boost/interprocess/vector.html
  seems to indicate this can be done. When I try to run the code
below, it fails with a "bus error" (on OS X) after printing "Entering
item in vector". What am I doing wrong? Also, how can I grow this
managed_mapped_file as I add things to the vector? I get runtime
errors using the managed_mapped_file::grow() function.

The code below should just fill up a vector with powers of 2, and
print it. I am trying to understand the library before I implement it
for something real.

Code below:

#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstddef>
#include <cstdio>
#include <cmath>

int main ()
{
    using namespace boost::interprocess;
    try{
      std::cout << "Starting" << std::endl;

      managed_mapped_file mfile (open_or_create, "MyMappedFile", 65536);

      std::cout << "Mapped file" << std::endl;

      typedef allocator<int, managed_shared_memory::segment_manager>
ShmemAllocator;
      typedef vector<int, ShmemAllocator> MyVector;
      const ShmemAllocator alloc_inst (mfile.get_segment_manager());

       std::cout << "Making vector" << std::endl;

       MyVector* vec = mfile.construct<MyVector>("vec")(alloc_inst);

       std::cout << "Made vector" << std::endl;

        std::cout << "Filling vector" << std::endl;

       int i = 0;
       for(i = 0; i < 63; ++i)
       {
          std::cout << "Entering item in vector" << std::endl;
          vec->push_back(pow(2,i));
          std::cout << "Entered item in vector" << std::endl;
       }

       std::cout << "Filled vector" << std::endl;

       std::cout << "Size of vec is:\t" << vec->size() << std::endl;

       std::cout << "Reverse printing contents of vector" << std::endl;

       for(i = vec->size()-1; i >= 0; --i)
       {
          std::cout << "At " << i << ":\t" << vec->at(i) << std::endl;
       }

       std::cout << "Printed contents of vector" << std::endl;
    }
    catch(interprocess_exception &ex){
       std::remove("MyMappedFile");
       std::cout << ex.what() << std::endl;
       return 1;
    }
    std::remove("MyMappedFile");
    return 0;
}



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net