C Windows API - close file handle before UnmapViewOfFile
Asked Answered
S

1

6

I am wondering if for this code snippet:

HANDLE fhandle = CreateFile("something.c", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
HANDLE mapping = CreateFileMapping(fhandle, NULL, PAGE_READONLY, 0, 0, NULL);
LPVOID map_view = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0);

The following order of releasing objects is valid:

CloseHandle(mapping);
CloseHandle(fhandle);
UnmapViewOfFile(contents);

i.e. can I close file handle first and call UnmapViewOfFile afterwards?

I know that execution order of CloseHandle(mapping) and UnmapViewOfFile(contents) is irrelevant, but what about closing the file handle?

I am asking because I would like to use only map_view pointer for destructor. It seems to me that this works and that the file is held until UnmapViewOfFile is called, but maybe this can cause some weird behavior?

Schottische answered 8/4, 2016 at 8:39 Comment(1)
Execution of these functions succeed in any order.Schottische
R
18

The documentation for UnmapViewOfFile explains:

Although an application may close the file handle used to create a file mapping object, the system holds the corresponding file open until the last view of the file is unmapped.

So yes, it is safe to close a file handle and still use the file mapping object created from that file handle. There are, however, implications with respect to sharing restrictions:

Files for which the last view has not yet been unmapped are held open with no sharing restrictions.

If you initially opened the file handle with sharing restrictions, those sharing restrictions aren't maintained by the internal handle. You have to decide whether this is permissible in your specific scenario.


Although not specifically asked, closing a file mapping object that is still mapped is also safe. From CreateFileMapping:

Mapped views of a file mapping object maintain internal references to the object, and a file mapping object does not close until all references to it are released. Therefore, to fully close a file mapping object, an application must unmap all mapped views of the file mapping object by calling UnmapViewOfFile and close the file mapping object handle by calling CloseHandle. These functions can be called in any order.

Ricebird answered 8/4, 2016 at 8:47 Comment(1)
Thanks. I missed the part.Schottische

© 2022 - 2024 — McMap. All rights reserved.