Pragya
Pragya

Reputation: 198

mmap() and munmap()

mmap() creates a new mapping in the virtual address space of the calling process starting at addr and len bytes and munmap() removes any mappings for those entire pages containing any part of the address space of the process starting at addr and continuing for len bytes.

I want to ask if the modified mmap files are written to disk by the munmap before releasing the memory or we have to call a different function to sync the modification.

Upvotes: 3

Views: 5917

Answers (1)

Andrew Henle
Andrew Henle

Reputation: 1

If you call mmap() with the MAP_PRIVATE flag, your changes will never be saved. If you use the MAP_SHARED flag, your changes will be saved without additional calls at some indeterminate time but before munmap() returns. And you can force the changes to be written to the file by using the msync() call.

Per the POSIX standard for mmap():

DESCRIPTION

...

MAP_SHARED and MAP_PRIVATE describe the disposition of write references to the memory object. If MAP_SHARED is specified, write references shall change the underlying object. If MAP_PRIVATE is specified, modifications to the mapped data by the calling process shall be visible only to the calling process and shall not change the underlying object. ...

...

The last data access timestamp of the mapped file may be marked for update at any time between the mmap() call and the corresponding munmap() call. The initial read or write reference to a mapped region shall cause the file's last data access timestamp to be marked for update if it has not already been marked for update.

The last data modification and last file status change timestamps of a file that is mapped with MAP_SHARED and PROT_WRITE shall be marked for update at some point in the interval between a write reference to the mapped region and the next call to msync() with MS_ASYNC or MS_SYNC for that portion of the file by any process. If there is no such call and if the underlying file is modified as a result of a write reference, then these timestamps shall be marked for update at some time after the write reference.

And per the munmap() documentation:

DESCRIPTION

...

If a mapping to be removed was private, any modifications made in this address range shall be discarded.

Upvotes: 2

Related Questions