Sharing memory between processes through the use of mmap()

Andrea Sprega picture Andrea Sprega · Feb 14, 2011 · Viewed 29.2k times · Source

I'm in Linux 2.6. I have an environment where 2 processes simulate (using shared memory) the exchange of data through a simple implementation of the message passing mode.

I have a client process (forked from the parent, which is the server) which writes a struct(message) to a memory mapped region created (after the fork) with:

message *m = mmap(NULL, sizeof(message), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0)

This pointer is then written to a queue (in form of a linked list) into another shared memory area which is common to server and client process (because if was created prior to fork with the same code above). This area is then read by the server which obtains the pointer to the message and processes it.

The problem is that *m is created after the fork() and when the server process tries to access the pointed memory location, i get a segmentation error. Is it possible to attach that region of memory to the server POST forking, after the client creates it?

NOTE: I don't want to mmap the pointer to message before forking (and then sharing it prior with the server) because I typically don't know how many messages the client wants to send to the server, and also there may be more than 1 client process, so I'd like to create a new block of shared memory only when a client needs to send a message, and unmap it after the server has received that message.

NOTE: This is for academic purpose: I know this is not the best way to solve this problem, but I just need to follow this path.

Thanks in advance!

Answer

Maxim Egorushkin picture Maxim Egorushkin · Feb 14, 2011

Is it possible to attach that region of memory to the server POST forking, after the client creates it?

MAP_ANONYMOUS|MAP_SHARED mapped memory can only be accessed by the process which does that mmap() call or its child processes. There is no way for another process to map the same memory because that memory can not be referred to from elsewhere since it is anonymous.

Using shm_open() call it is possible to create named shared memory which can be referred to and mapped by unrelated processes.