Mmap: effect of other processes writing to a file previously mapped read-only

cmmap

I am trying to understand what happens when a file, which has been mapped into memory by the mmap system call, is subsequently written to by other processes.

I have mmaped memory with PROT_READ protection in "process A". If I close the underlying file descriptor in process A, and another process later writes to that file (not using mmap; just a simple redirection of stdout to the file using > in the shell), is the mmaped memory in the address space of process A affected? Given that the pages are read-only, I would expect them not to change. However, process A is being terminated by SIGBUS signals as a result of invalid memory accesses (Non-existent physical address at address 0x[...]) when trying to parse the mapped memory. I am suspecting that this is stemming from writes to the backing file by other processes. Would setting MAP_PRIVATE be sufficient to completely protect this memory from other processes?

Best Answer

If I close the underlying file descriptor in process A,

closing the file descriptor doesn't change anything at all

another process later writes to that file (not using mmap; just a simple redirection of stdout to the file using > in the shell), is the mmaped memory in the address space of process A affected?

It may be. The manpage of mmap(2) says:

 MAP_PRIVATE
    ...
    It is  unspecified  whether changes made to the file
    after the mmap() call are visible in the mapped region.

In practice, changes made by other processes seem to be reflected in the content of the mmaped region, at least for regular files.

However, process A is being terminated by SIGBUS signals as a result of invalid memory accesses (Non-existent physical address at address 0x[...]) when trying to parse the mapped memory.

I'm expecting that to happen when you truncate a mmaped file.

Would setting MAP_PRIVATE be sufficient to completely protect this memory from other processes?

No, MAP_PRIVATE only prevent modifications to the memory from being carried through to the backing file, not the reverse.

Related Question