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?)
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With