Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mmap same file, same physical memory?

Tags:

c

linux

mmap

Suppose I:

  1. open a read-only file F of N byte length from a process A
  2. mmap its fd read-only (PROT_READ) and MAP_SHARED
  3. mlock the returned memory range.
  4. go into an infinite loop.

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?

like image 650
Andrew Tomazos Avatar asked Mar 05 '26 14:03

Andrew Tomazos


1 Answers

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.

like image 99
Maxim Egorushkin Avatar answered Mar 08 '26 06:03

Maxim Egorushkin