Two C ++ applications sharing read-only memory in Linux

I have two processes P1 and P2.

I have this large read-only resource called "R", which I want to get both P1 and P2.

R is not just a β€œflat” group of bytes; this is a bunch of C ++ objects that point to each other.

I would prefer that P1 and P2 share only one copy of R - one way or another, it would load R1 R in the memory area (which is modeled in P1 and P2 with the same address), then P1 and P2 can simultaneously access objects in R as C ++ objects (without race conditions, since everything is read-only).

Does anyone know how to do / gotchas?

+4
source share
4 answers

In fact, something similar was set and resolved before :

And the best answer will probably work for you: Use a larger library of interprocesses . Although you still cannot use objects with virtual functions (a nasty vtable pointer outside of the shared memory problem), they have tools that allow you to use smart pointers for other objects inside shared memory and custom allocators that allocate inside the shared memory to create std :: vector and std :: map objects.

+5
source

How do objects inside R point to each other? If this position is β€œrelative to the current object”, you can use shared memory . There is no guarantee that this shared memory is loaded inside both processes P1 and P2 at the same address location. That is why relative only works. And since you said, none of them will try to change it and just read from it, I think you do not need to protect it using a semaphore / mutex.

+1
source

If I understand the help page, it seems that the Linux mmap function allows you to map a file, shared memory, or other mapped files to your process at a specific virtual address if you provide a somewhat frightening MAP_FIXED sound. Find the man page for MAP_FIXED and you will find many warnings (maybe not supported, maybe malloc is no longer working, etc.). But if you can make it work, shared objects can have pointers to each other.

+1
source

It is so simple:

#include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> // ... int fd = open("memfile.txt",O_RDWR); struct stat info; fstat(fd, &info); void * page = mmap(0, info.st_size, PROT_READ , MAP_SHARED, fd, 0); 

Now you can use everything that you saved in memfile.txt as a structure, and it will be shared between processes.

NOTE , as others have stated, you cannot use pointers between objects inside this piece of memory.

This works for me on OS X 10.4, but should work on any BSD-compatible system.

0
source

All Articles