5

What I want is to access the data info of an managed shared memory object using a class named ShmObj with the raw pointer to the shared objects as private member, as code blocks below.

My problem is the main program segmentation fault. I guess the absolute raw pointer causes the problem. I tried to change the raw pointer to bi::offset_ptr but doesn't help. Any help is appreciated.

ShmObj.h

#include <string>
#include <boost/interprocess/managed_shared_memory.hpp>
namespace bi = boost::interprocess;

class ShmObj {
public:
    ShmObj() {
        bi::managed_shared_memory segment(bi::open_only, "shm");
        pNum = segment.find<int>("Number").first;
    }
    int getNumber() {return *pNum;}
    virtual ~ShmObj() {}

private:
    int* pNum;
};

main.cpp

#include "ShmObj.h"
#include <iostream>

int main() {
    ShmObj X;
    std::cout << X.getNumber() << std::endl;
}
manlio
  • 18,345
  • 14
  • 76
  • 126
ZFY
  • 135
  • 12

1 Answers1

4

Your shared memory segment is destructed at the end of the constructor... Move it to a field to extend its lifetime:

#include <string>
#include <boost/interprocess/managed_shared_memory.hpp>
namespace bi = boost::interprocess;

class ShmObj {
public:
    ShmObj() 
      : segment(bi::open_or_create, "shm", 32ul*1024),
        pNum(0)
    {
        pNum = segment.find_or_construct<int>("Number")(0);
    }

    int getNumber() {
        assert(pNum);
        return *pNum;
    }

    virtual ~ShmObj() {}

private:
    bi::managed_shared_memory segment;
    int* pNum;
};

#include <iostream>

int main() {
    ShmObj X;
    std::cout << X.getNumber() << std::endl;
}
sehe
  • 374,641
  • 47
  • 450
  • 633
  • Why can't we do `pNum(segment.find_or_construct("Number")(0))` also in the initializer list? – CinCout Oct 13 '14 at 11:38
  • You can, have you tried? Anyways, for anything non-trivial I'd really **not** do that in the initializer-list unless you have a suitable **[Rule-Of-Zero](http://flamingdangerzone.com/cxx11/2012/08/15/rule-of-zero.html)** resource wrapper to make it exception safe if the construction throws. Consider: http://paste.ubuntu.com/8552394/ – sehe Oct 13 '14 at 13:04