I cannot share a pointer to an object among processes with shared memory.
I can successfully share a struct like the one below among different processes:
// Data to be shared among processes
struct Shared_data {
int setPointCounter;
struct Point old_point;
pthread_mutex_t my_mutex;
} *shd;
The struct is declared as global (it is located before the main(), let's say).
I initialize the shared memory into the main:
shd = (struct Shared_data *) (mmap(NULL, sizeof *shd, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0));
and then at a certain point I do a fork(). It works fine.
The problem arises when I have to share something like this:
// Data to be shared among processes
struct Shared_data {
int setPointCounter;
struct Point old_point;
MyObject *obj;
pthread_mutex_t my_mutex;
} *shd;
In the main I call a function from a third-party library which returns a pointer to an object of MyObject type and I would like to share it in some way. How can I do this?
By searching on the web I've found something related to relative pointers but I'm not sure it will work and, at the same time, I don't know how to do it the right way.
I'm working on Linux (Slackware 64 14.2) and the language is C/C++ (mostly is C, actually).
Thank you in advance for your time.
Basically a pointer is an address of some data in the virtual space of one process. You cannot share pointers between processes because those pointers will be interpreted in a different address space (in general, this also applies to the kernel mode virtual space and the user mode of the same process). Let's use an example... you have make some allocations (between them you have made a mmap(2)
allocation) and then you fork(2)
another process. Until then, all memory addresses pointed to the same places if we consider that both processes had existed before the fork, they would have been doing the same, getting the same results, etc.
But once both processes depart from each other, all the allocations made in one process can be differently positioned than the same allocations in the other process, as the different histories of each process could provide different results from any allocator. Just assume some temporal order in the tasks and some time dependant state change... after it, the states of both processes will be different.
Now let's suppose you have a pointer in one process, that points to an structure of data, that you want to share with the other. But the other process has not even allocated the same thing... so passing e.g. 0x00456211ff
to the other process will point to a place in the other process where nothing has been allocated (leading to a SIGSEGV
signal and process abort)
Once the processes divert their virtual spaces store different things, and virtual pointers in one space are not interpretable in the other process'.