> I want to create a single data structure in shared memory and use it from
> number of processes using semaphores and appropriate access privileges. I
> should be able to dynamically cast the heap in different processes and then
> use it. I can rephrase my question as follows;
> I need to know a way where by I can create a data structure in shared memory
> i.e. when I say new to create an object I should be able to create the object
> with staring address of shared memory.
> Please help....
I can think of two ways to do this either by using a shared
memory segment or a shared memory mapped file.
The shared memory segment can be allocated using shmget,
mapped using shmat, and deleted using shmctl.
The file is created using open or creat, mapped using mmap,
resized using truncate, and deleted using unlink.
Which solution you should use depends on the lifetime of
the datastructure. If the datastructure should exist even
at times when no program is using it I suggest files, if
the datastructure should be deleted when the last process
stops using it you can use a shared memory segment.
You cannot expect to map the structure at same address in
all processes, so shared memory should never contain
pointers. Instead of pointers write offset in bytes from
start of shared memory.
You might have to write some routines to handle allocation
and deallocation of shared memory. For example you could
implement two routines:
int shared_malloc(size_t size);
void shared_free(int ptr);
I don't know about synchronisation, but I would expect
file locks using fcntl would work for the file solution.
I don't know if you can allocate C++ objects in the shared
memory, but I can point out lots of potential problems.
Imagine the problem when an object created by one
executable is at a later mapped by another executable. The
executables could be two different programs or just two
different versions of the same program. The objects class
might not exist in the other executable, or if it exists
the methods could have changed or just be located at
another address in the executable.