正在将最后一个 link 删除到安全的内存映射文件

Is removing the last link to a memory mapped file safe

有时我会使用下面的代码来读取文件(省略错误检查代码):

db = open(db_path, O_RDONLY);
fstat(db, info);
buffer = mmap(0, info->st_size, PROT_READ, MAP_PRIVATE, db, 0);
close(db);

请注意,我在调用 mmap 后关闭文件。然后一旦我完成 buffer:

munmap(buffer, info->st_size);

如果有人从文件系统中删除文件的最后一个 link(例如 unlink(db_path))并且没有进程具有该文件的文件描述符,会发生什么情况?这会导致未定义的行为还是操作系统会保留文件直到它被取消映射?我找不到明确说明其中之一的文档。

来自the official POSIX reference on mmap

The mmap() function shall add an extra reference to the file associated with the file descriptor fildes which is not removed by a subsequent close() on that file descriptor. This reference shall be removed when there are no more mappings to the file.

因此在 munmap 调用之前使用映射文件是安全的。