• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 366
  • Last Modified:

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?
0
chsalvia
Asked:
chsalvia
1 Solution
 
efnCommented:
You're right, that would not be safe.  However, a self-contained object in shared memory could be shared between processes.  Or an object that was not self-contained could be shared if you were careful.  The memory not contained in the object would have to be in some shared memory area, and you would have to manage it yourself, using offsets from the beginning of the shared memory area.  That is, the usual malloc or new facilities won't manage a shared memory area for you, and its address will not necessarily be the same in all processes that use it, so pointers within it are not portable across processes, and you will have to use offsets from the beginning of the area to identify locations portably.
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now