Search code examples
cmacossystem-callsmmap

Memory mapped file cannot be closed without un-mapping, since it's still referenced


I'm getting scenario in macOS where I cannot close memory mapped file without un-mapping it first (using munmap syscall), although the close syscall return success result (=0) I can still see the file record in lsof -n.

In linux, it's explicitly mentioned that closing the file doesn't unmap the file, according to mmap man page.

Is it indeed a different behavior between the 2 OSes ? Is there any explanation for this different behavior ?

EDIT: after reading the comments below, I've realized that there's no different behavior between the platforms, and that the reason why my file still opened is because it's still referenced by the mmap.

thanks


Solution

  • POSIX requires that there's a reference to mmap'ed file even after a close.

    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.

    And that's what lsof sees there's a reference to that file. So it's working as documented.