0

The mmap man pages indicate that closing a file does not result in unmapping of pages. However, I wonder if the following sequence is valid that by the time the read occurs the pages have likely not have been faulted into memory. In other words, is the file still open after the close ? Also is the behavior expected on both Android and iOS?

void func()
{
   auto fd    = open("test.txt", O_RDONLY);
   void *ptr  = mmap(nullptr, 16384, PROT_READ, MAP_PRIVATE, fd, 0);
   close(fd);
   uint8_t *p = (uint8_t *)ptr;
   // Read from *p 
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
user3882729
  • 1,339
  • 8
  • 11
  • You should try it and post an update on if it worked. In theory this shouldn't work at all. – wxz May 10 '21 at 18:33
  • it works and hence my question, if it's always expected to work – user3882729 May 10 '21 at 18:40
  • Interesting. Curious to know the answer – wxz May 10 '21 at 18:42
  • Does this answer your question? [Do I need to keep a file open after calling mmap on it?](https://stackoverflow.com/questions/17490033/do-i-need-to-keep-a-file-open-after-calling-mmap-on-it) – wxz May 10 '21 at 18:45
  • Seems like mmap adds its own reference to the file so the `fd` is closed, but mmap's internal reference is still open which is why it works. – wxz May 10 '21 at 18:46
  • mmap adds a reference. If you close and unlink the file, the disk space will not be freed until you unmap. – stark May 10 '21 at 18:52

0 Answers0