3

If I call msync with MS_ASYNC on a memory mapped region, the sync process will be handled asynchronously.

However, if I call munmap immediately on that region, can I assume that the msync will be carried out safely? Or will I have to call msync before munmap?

kamziro
  • 7,882
  • 9
  • 55
  • 78

1 Answers1

3

The short answer is yes -- the changes to the contents will eventually (and safely) make their way to the file, even if you never call msync. From man 2 mmap:

MAP_SHARED
          Share this mapping.  Updates to the mapping are visible to other
          processes that map this file, and 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).)

Perhaps more to the point, man 2 msync has this note:

Since Linux 2.6.19, MS_ASYNC is in fact a no-op, since the kernel properly tracks dirty pages and flushes them to storage as necessary.

Remember: mmap is directly exposing pages of the filesystem cache to userspace and, just like any other caching system, changes will be propagated to the backing storage at some point in the future. Even if your program crashes, the changes you made to the pages will eventually get propagated. The use of msync is to protect you from things like power loss.

Travis Gockel
  • 26,877
  • 14
  • 89
  • 116