C Windows API - 在 UnmapViewOfFile 之前关闭文件句柄

C Windows API - close file handle before UnmapViewOfFile

我想知道是否对于这个代码片段:

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);

以下释放对象的顺序是有效的:

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

即我可以先关闭文件句柄然后再调用 UnmapViewOfFile 吗?

我知道CloseHandle(mapping)UnmapViewOfFile(contents)的执行顺序无关紧要,但是关闭文件句柄呢?

我问是因为我只想对析构函数使用 map_view 指针。在我看来,这是有效的,并且文件一直保存到 UnmapViewOfFile 被调用,但也许这会导致一些奇怪的行为?

UnmapViewOfFile 的文档说明:

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.

所以是的,关闭文件句柄并仍然使用从该文件句柄创建的文件映射对象是安全的。但是,在共享限制方面存在一些影响:

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

如果您最初打开带有共享限制的文件句柄,则这些共享限制不会由内部句柄维护。您必须决定在您的特定情况下是否允许这样做。


虽然没有特别要求,但关闭一个仍然被映射的文件映射对象也是安全的。来自 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.