Sometimes I use the following code piece to read files (error checking code omitted):
db = open(db_path, O_RDONLY);
fstat(db, info);
buffer = mmap(0, info->st_size, PROT_READ, MAP_PRIVATE, db, 0);
close(db);
Note that I'm closing the file after the call to mmap. Then once I'm done with buffer
:
munmap(buffer, info->st_size);
What will happen if somebody deletes the last hard link to the file from the filesystem (e.g. unlink(db_path)
) and no process has a file descriptor to the file? Will this cause undefined behavior or is the operating system keeping the file until it is unmapped? I couldn't find documentation that explicitly states one or the other.
From 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 subsequentclose()
on that file descriptor. This reference shall be removed when there are no more mappings to the file.
So it's safe to use the mapped file until the munmap
call.