Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing Pointers Between Multiple Forked Processes

If I want to share something like a char **keys array between fork()'d processes using shm_open and mmap can I just stick a pointer to keys into a shared memory segment or do I have to copy all the data in keys into the shared memory segment?

like image 970
user1743798 Avatar asked Oct 05 '13 17:10

user1743798


People also ask

What is shared between forked processes?

Answer: Only the shared memory segments are shared between the parent processparent processIn computing, a parent process is a process that has created one or more child processes.https://en.wikipedia.org › wiki › Parent_processParent process - Wikipedia and the newly forked child process. Copies of the stack and the heap are made for the newly created process.

Can 2 processes share memory?

Context switching between processes is more expensive. Processes don't share memory with other processes. Threads share memory with other threads of the same process.

Do forks share memory?

Threads. While fork copies all of the attributes we mentioned above, imagine if everything was copied for the new process except for the memory. This means the parent and child share the same memory, which includes program code and data.


1 Answers

All data you want to share has to be in the shared segment. This means that both the pointers and the strings have to be in the shared memory.

Sharing something which includes pointers can be cumbersome. This is because mmap doesn't guarantee that a given mapping will end up in the required address.

You can still do this, by two methods. First, you can try your luck with mmap and hope that the dynamic linker doesn't load something at your preferred address.

Second method is to use relative pointers. Inside a pointer, instead of storing a pointer to a string, you store the difference between the address of the pointer and the address of the string. Like so:

char **keys= mmap(NULL, ...);
char *keydata= (char*) keys + npointers * sizeof(char*);
strcpy(keydata, firstring);
keys[0]= (char*) (keydata - (char*) &keys[0]);
keydata+= strlen(firststring)+1;

When you want to access the string from the other process, you do the reverse:

char **keys= mmap(NULL, ...);
char *str= (char*) (&keys[0]) + (ptrdiff_t) keys[0];

It's a little cumbersome but it works regardless of what mmap returns.

like image 114
dodo Avatar answered Sep 23 '22 00:09

dodo