Sharing memory between processes through the use of mmap()

Question!

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!



Answers

That's not going to work.

If you create a mapping after the fork(), it won't be the same in the other related process(es).

You can't assume the sharing of pointers in this way.

If you really want to do it this way (I would not recommend it!), you should mmap a big area before the fork(), then allocate somehow, buffers of a suitable size (without race conditions with other processes, of course!) and pass those pointers.

Two related processes which call mmap() after a fork, may get the same pointer back, pointing at different memory. In fact this is extremely likely.

By : MarkR


This video can help you solving your question :)
By: admin