Suppose I:
open a read-only file F of N byte length from a process Ammap its fd read-only (PROT_READ) and MAP_SHAREDmlock the returned memory range.My understanding is the data from the file is now resident and backed by N bytes of physical memory pages, due to the mlock. The read performance of the memory range should be the same as normal memory allocated with, say, malloc.
Now, if I create a second process B while the process A is still running and do exactly the same steps from process B, will the N bytes of physical memory pages that back the mmaped file be the same physical pages from process A?
That is, will A and B together use N bytes of physical memory? Or will they use 2*N bytes of physical memory?
When you map a file the pages come from the kernel page cache which maintains the kernel view of the file. There is only ever one view of the same file in the kernel. When you map the file more than once (regardless from which process), the mapped pages are the very same physical pages from the kernel page cache.
Otherwise, it would be prohibitively expensive to maintain different pages of memory in sync when one process modifies its MAP_SHARED file mapping.
In other words, processes A and B together share the same N bytes of physical memory used to map the same file.
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