What is the behavior of the mmap () 'ed pointer after closing the file descriptor without first calling munmap ()?

Consider the following code snippet:

#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 to be smaller than 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 to munmap

   close(fd);

   printf( "%d\n", data[0]);        // <-- why doesn't this segfault

}

Background

I work with a custom kernel driver, which it uses ioctl()to configure for DMA and ultimately requires the user space to use mmap()to access a specific buffer.

When developing unit tests, I accidentally discovered that after closing the file descriptor without calling it munmap, firstly, you could still access the buffer memory in user space using the mmap'ed pointer. Thinking that there was an error in the driver, I wrote a small program, similar to the one given here, to implement mmap () with a "normal" file.

, , - segfault , , ​​ munmap() , , , , .

. , mmap() , , , ( , ), , . mmap .

segfault , , , , .

, * nix? , , segfault? , , vm-?

+5
2

, , , : mmap ?

POSIX, - man ( munmap, : - |) , . , , , , segfault .

, - .

+9

man mmap :

mmap() fd .

2018 , Linux 5.x.

0

Source: https://habr.com/ru/post/1546096/


All Articles