Dear Ion,
First of all thanks for your fast reply. I have modified the code as
suggested by you. The segmentation fault has disappeared. I do not
want to be a pest... however, Could you please explain me why there
was a segmentation fault before?
I know that the way I synchronized was not good before doing the
example. However, from the cout I supposed that the segment was
created before pressing a key (If you take a look to the code). I
neither understand why I was able to execute find<> without an
exception.
Could you please give me some more explanation?
This is the code that works...
#include <iostream>
#include
#include
#include
namespace ip=boost::interprocess;
class OffsetPtrClass {
public:
OffsetPtrClass():myint_(0) {
//If we allocate the int here we get a segmentation fault!!
//
ip::managed_shared_memory segment(ip::open_only,"MySharedSegment");
myint_ = static_cast(segment.allocate(sizeof(int)));
}
~OffsetPtrClass() {
}
void setMyint(const int& myint) {
*myint_ = myint;
}
int getMyint() {
int myint = *myint_;
return myint;
}
ip::offset_ptr<int> myint_;
};
int main( int argc, char* argv[] ) {
std::string shName("MySharedSegment");
{
ip::shared_memory_object::remove(shName.c_str());
try{
std::cout << "PARENT: creating segment" << std::endl;
ip::managed_shared_memory segment(ip::create_only, shName.c_str(), 65536);
std::cout << "PARENT: creating OffsetPtrClass 'optr' instance"
<< std::endl;
OffsetPtrClass& optr = *(segment.construct<OffsetPtrClass>("optr")());
//If we allocate the int here we do not have a segmentation fault
optr.myint_ = static_cast(segment.allocate(sizeof(int)));
std::cout << "PARENT: 'optr'::SetMyint(333)" << std::endl;
optr.setMyint(333);
std::cout << "PARENT: 'optr'::getMyint() = " << optr.getMyint()
<< std::endl;
std::cout << "PARENT: 'optr'::*myint_() = " << *(optr.myint_) <<
std::endl;
//std::cout << "PARENT: press return to continue..." < res;
res = segment.find<OffsetPtrClass> ("optr");
assert(res.second == 1);
OffsetPtrClass& optr =*(res.first);
std::cout << "CHILD: 'optr'::getMyint() = " << optr.getMyint()
<< std::endl;
std::cout << "CHILD: 'optr'::SetMyint(100)" << std::endl;
optr.setMyint(100);
} catch (...) {
std::cerr << "CHILD: Something failed..." << std::endl;
throw;
}
} else if (pid <0){
std::cerr << "---program.cc: Failed to fork" << std::endl;
exit(1);
} else {
std::cout << "PARENT: getpid() = " << getpid() << std::endl;
}
}
Thank you very much,
marc
PS: I have not replied directly to the message you send because I had
the "digest" mode on. Sorry for the inconvenience.