Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost interprocess managed shared memory raw pointer as a class member

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;
}
like image 851
ZFY Avatar asked Sep 30 '22 16:09

ZFY


1 Answers

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;
}
like image 96
sehe Avatar answered Oct 20 '22 17:10

sehe