Link to home
Start Free TrialLog in
Avatar of chsalvia
chsalvia

asked on

putting objects into shared memory regions

Using the shmget and shmat function you can allocate a block of memory that multiple processes can access.  But suppose you want to store an object in that memory.  So you copy the object to the shared memory using memcpy, and then any process can access it with an object* pointer.  

This seems like it would work fine.  But what if the object itself contains an internal pointer to another memory location?

For example, suppose you have:

class Box {
     char* p;

     public:
     Box() { p = new char[100]; }
     ~Box() { delete[] p; }
     char* data() { return p; }
};

And then you do:

Box box;
void* sharedmem = shmat(shmid, (void*) 0, 0);
memcpy (sharedmem, &box, sizeof(box));

Now a copy of the object "box" is in the shared memory region.  So, I set a pointer to it like:
Box* pbox = (Box*) sharedmem;

And then I can access the data in Box by doing:
pbox->data();

But wouldn't this cause a segmentation violation if another process tried to access the data in box?  Because even though box itself is stored in the shared memory region, the data pointed to by the member variable of box is NOT in the shared memory region, and is in fact, part of another process.  So wouldn't this be an unsafe thing to do?  If so, is there any possible way to share objects between processes?
ASKER CERTIFIED SOLUTION
Avatar of efn
efn

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial