mmap() 和 munmap()

mmap() and munmap()

mmap() 在调用进程的虚拟地址 space 中从 addrlen 字节开始创建新映射,并且 munmap() 删除所有映射对于那些包含从 addr 开始并持续 len 字节的进程的地址 space 的任何部分的整个页面。

我想问一下修改后的mmap文件是在释放内存之前由munmap写入磁盘还是我们必须调用不同的函数来同步修改。

如果您使用 MAP_PRIVATE 标志调用 mmap(),您的更改将永远不会被保存。如果您使用 MAP_SHARED 标志,您的更改将在某个不确定的时间但在 munmap() returns 之前保存而无需额外调用。您可以使用 msync() 调用强制将更改写入文件。

根据 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.

根据 the munmap() documentation:

DESCRIPTION

...

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