0

I am curious to know the details of how the kernel deals with concurrent writes / access to a shared mapping created through mmap. Looking in the man pages, all that I see for MAP_SHARED is the following:

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 precisely control when updates are carried through to the underlying file requires the use of msync(2).)

However, from my understanding, msync is dealing with synchronization from the page cache to the underlying storage device. However, it doesn't seem to deal with the case that two processes have mmaped a file. What happens when two processes write to the mapped region at the same time? If I create a shared mapping, how can I be sure that an unrelated process that happens to map the same file isn't doing concurrent writes?

rb612
  • 5,280
  • 3
  • 30
  • 68

1 Answers1

1

The kernel on its own isn't going to do anything to prevent multiple processes (or even threads within a single process) from trashing the shared memory contents. You have to use synchronization constructs (such as a mutex) and ensure that all code that accesses the shared memory agrees on how to go about it.

The way to protect against another process simply writing to the file is to use flock before mmapping the region. You then need some way for the process that performs the mapping to communicate the file descriptor to the second process.

The answer to this question suggests using unix file sockets for that purpose.

SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23