What I actually want to do is to redirect writes in a certain memory area to a separate memory area which is shared between two processes. Can this be done at user level? For example, for some page X. What I want to do is to change its (virtual to physical) mapping to some shared mapping when it’s written. Is this achievable? I need to do it transparently too, that is the program still uses the variables in page X by their names or pointers, but behind the scenes, we are using a different page.
Share
Yes, it is possible to replace memory mappings in Linux, though it is not advisable to do it since it is highly non-portable.
First, you should find out in what page the
Xvariable is located by taking its address and masking out the last several bits – query the system page size withsysconf(_SC_PAGE_SIZE)in order to know how many bits to mask out. Then you can create a shared memory mapping that overlaps this page using theMAP_FIXED | MAP_SHAREDflag tommap(2)ormmap2(2). You should copy the initial content of the page and restore it after the new mapping. Since other variables may reside in the same page, you should be very careful about memory layout and better use a dedicated shared memory object.