Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between mmap MAP_SHARED and MAP_PRIVATE when PROT_READ is also used?

If I create an mmap(2) of a file with a prot parameter of PROT_READ only and the file backing it is also read-only and does not change, is there any performance difference (or any difference at all) between MAP_SHARED and MAP_PRIVATE ? Will the kernel do something differently between the two?

(The documentation only refers to difference of behaviour in terms of "updates", but as it is PROT_READ there can be no updates. I wonder if there is some other difference?)

like image 803
Andrew Tomazos Avatar asked Jan 19 '13 23:01

Andrew Tomazos


People also ask

What is Map_shared?

Following are some common values of the flags: MAP_SHARED: This flag is used to share the mapping with all other processes, which are mapped to this object. Changes made to the mapping region will be written back to the file.

What is Map_private?

MAP_PRIVATE Create a private copy-on-write mapping. Updates to the mapping are not visible to other processes mapping the same file, and are not carried through to the underlying file. It is unspecified whether changes made to the file after the mmap() call are visible in the mapped region.

What is mmap () used for?

The mmap() function can be used to map a region of memory that is larger than the current size of the object. Memory access within the mapping but beyond the current end of the underlying objects may result in SIGBUS signals being sent to the process.

What does the Map_anonymous do in combination with mmap?

MAP_ANONYMOUS + MAP_SHARED: each call creates a distinct mapping that doesn't share pages with any other mapping. children inherit parent's mappings. no copy-on-write when someone else sharing the mapping writes on the shared mapping.


1 Answers

Under MAP_PRIVATE, the Linux manpage says that it is unspecified whether changes made to the file after the mmap() call are visible in the mapped region. That is not the case with MAP_SHARED. So if you need the contents of the mapping to be updated together with the contents of the file, you had better use MAP_SHARED. If the underlying file itself is read-only and cannot change then of course none of this is applicable.

If PROT_READ is used, I can see nothing else that should be different between MAP_PRIVATE and MAP_SHARED. In fact, despite the above warning about unspecified behaviour, my guess (which I have not tested) would be that in practice there is no difference at all between the two under PROT_READ.

like image 59
Celada Avatar answered Oct 14 '22 14:10

Celada