Reputation: 68728
Suppose I:
open
a read-only file F
of N
byte length from a process A
mmap
its fd
read-only (PROT_READ
) and MAP_SHARED
mlock
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?
Upvotes: 3
Views: 1622
Reputation: 136515
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.
Upvotes: 4
Reputation: 5675
In modern operating systems, when 2 programs map the same file, each process has its own page table for its memory, that may point to pages of physical memory shared with other user and kernel processes.
With MAP_SHARED
, this mapping is shared: updates to the mapping are visible to other processes that map this file, and are carried through to the underlying file. The file may not actually be updated until msync
or munmap()
is called.
Upvotes: 0