Samuel Hapak
Samuel Hapak

Reputation: 7192

Two processes mmap same file on linux, when is the memory shared?

Under what circumstances is the physical memory backing mmap of the same file shared between processes in linux?

I understand, that the necessary condition is MAP_SHARED. I understand, that if the processes use same file descriptor (e.g., child inheriting it from parent), the memory will be shared.

But what happens if, e.g.,

Upvotes: 1

Views: 1527

Answers (1)

Dan Bonachea
Dan Bonachea

Reputation: 2477

See this part of the Linux man page for mmap():

MAP_SHARED
Share this mapping. Updates to the mapping are visible to other processes mapping the same region, and (in the case of file-backed mappings) are carried through to the underlying file.

To answer your specific questions:

  1. It doesn't matter whether the processes are forked and using the same file descriptor, or independently opened the same file (even via different path names). All the matters is they've mapped the same file, as determined by inode on the filesystem, and then invoked mmap(MAP_SHARED).
  2. The O_RDWR mode of the file descriptor controls whether it's permitted for that process to pass PROT_WRITE, otherwise the mmap() call from that process will fail with EACCESS, (from the same man page):

Errors:
EACCES
file mapping was requested, but fd is not open for reading. MAP_SHARED was requested and PROT_WRITE is set, but fd is not open in read/write (O_RDWR) mode. Or PROT_WRITE is set, but the file is append-only.

  1. The PROT_READ/PROT_WRITE flags control the readability/writeability of the virtual page table entries created in the corresponding process who made the mmap() call (and hence that process's ability to read and write). This has no effect on other processes mapping the same file pages (who might differ in read/write access based on the flags to their own mmap call).

Authoritative pages with additional information and some useful examples:

  1. IBM's mmap documentation
  2. GNU libc documentation for mmap
  3. linuxhint.com blog article

Upvotes: 2

Related Questions