tags:

views:

239

answers:

1

Does protection flag affect the sharing between processes? If I have PROT_READ|PROT_WRITE -protected mmapped memory region, is it still fully shared as long as I haven't written into it?

int prot = PROT_READ|PROT_EXEC;
image = mmap(NULL, filesize, prot, MAP_PRIVATE, fildes, 0);

vs:

int prot = PROT_READ|PROT_WRITE|PROT_EXEC;
image = mmap(...)

I'd want to make small modification to small portion of the memory region after I've mapped it, then re-mprotect it all, because it's simpler than mprotecting small portions when I need to do so.

The question is whether it ends up forcing the whole file copied per process or just the portions I modified per process?

+1  A: 

According to the mmap(2) man page on a recent Linux system, MAP_PRIVATE allocates the memory using copy-on-write (COW). This means, your memory will not be duplicated unless you make changes to it. As COW is an efficient method to implement this, I assume it is also done this way in other *NIX systems.

The memory for mmap is organized in equal-sized chunks, so called pages. Memory will always be mapped in multiples of the page size, i.e. whole pages. Each page can be swapped independently. So if you write something to this mmap'ed memory range, only at least one page has to be copied.

The page size depends on your system, on x86 it is usually 4096 bytes. If you are interested in the page size of your system, you can use sysconf(3).

   #include <unistd.h>
   long pagesize = sysconf(_SC_PAGESIZE);

The pointer you get from mmap() will already point to a multiple of the page size and you should pass mprotect() an address being aligned to a page boundary.

Raim