c - What is the behaviour of an mmap()'ed pointer after closing the file descriptor without first calling munmap()? -


consider following code fragment:

#include <stdio.h> #include <unistd.h> #include <sys/mman.h> #include <fcntl.h>  int fd = open( "/path/to/existing/file/or/device", o_rdonly); int numberofwords = 4096; // chosen smaller file size int* data = mmap( null, nomberofwords * sizeof(int), prot_read, map_shared, fd, 0);  if (data != map_failed) {     printf( "%d\n", data[0]);     // oops, forgot munmap     close(fd);     printf( "%d\n", data[0]);        // <-- why doesn't segfault  } 

background

i working custom kernel driver uses ioctl() setup dma, , requires user space use mmap() access particular buffer.

while developing unit tests discovered accidentally after closing file descriptor without calling munmap first, still possible access buffer memory in user space mmap'ed pointer. thinking there bug in driver wrote small program similar shown here exercise mmap() "normal" file.

what expecting see segfault on read after close, thinking being, kernel automatically munmap() pages associated file descriptor when use of open file descriptor closed, similar how happens when process terminated.

instead, able keep using pointer. bit surprising have been using mmap() several years, must have been smart (more lucky) enough avoid bugs expose situation. nothing obvious in mmap man page.

problem

ideally our driver need cause segfault in user space if happens, because don't want buggy user space program writing memory of interest.

so, behaviour same across different *nix? in given example, take deleting file cause segfault? or perhaps flushing vm caches?

ok, after writing of question found different question worded differently how searching: do need keep file open after calling mmap on it?

the answer references posix manual , turns out in man page after (under munmap, in passing :-| ) explained closing descriptor not automatically unmap mapping. looks need modify our driver close code invalidate associated memory mappings segfault occur in user space.

i decided post question in case else searches similar thing.


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -