gpt4 book ai didi

c++ - Windows 上 MapViewOfFile 的引用计数问题

转载 作者:可可西里 更新时间:2023-11-01 13:33:54 25 4
gpt4 key购买 nike

看来MapViewOfFile增加了文件映射内核对象的引用计数。

引自 MapViewOfFile 的 MSDN 描述:

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.

另外,从 Windows via C/C++,第 5 版:

The preceding code shows the "expected" method for manipulating memory-mapped files. However, what it does not show is that the system increments the usage counts of the file object and the file-mapping object when you call MapViewOfFile...

尽管如此,我的实际测试表明情况恰恰相反。我在 Windows 10 64 位上使用 Visual Studio 2015。测试程序如下:

#include <windows.h>

int main() {
HANDLE h = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 128, "test");
void* p_memory = MapViewOfFile(h, FILE_MAP_WRITE, 0, 0, 0);
CloseHandle(h);
h = OpenFileMappingA(FILE_MAP_WRITE, FALSE, "test");
DWORD dw = GetLastError(); // ERROR_FILE_NOT_FOUND
}

OpenFileMapping 调用失败,出现最后一个错误 ERROR_FILE_NOT_FOUND。当我删除 CloseHandle 调用时,一切都会好起来的。这意味着 CloseHandle 调用消除了文件映射内核对象的最后引用计数并将其销毁。这反过来意味着 MapViewOfFile 实际上并没有增加对象的引用计数。

我想确定发生了什么,MapViewOfFile 关于文件映射内核对象的引用计数的确切语义是什么。

最佳答案

您可以通过使用文件而不是页面文件作为后备存储来使其更具说服力:

int main() {
const char* path = "mmf.bin";
DeleteFile(path);
HANDLE hFile = CreateFile(path, GENERIC_READ | GENERIC_WRITE,
FILE_FLAG_DELETE_ON_CLOSE,
NULL, CREATE_NEW, 0, NULL);
HANDLE h = CreateFileMappingA(hFile, NULL, PAGE_READWRITE, 0, 128, "test");
int* p_memory = (int*)MapViewOfFile(h, FILE_MAP_WRITE, 0, 0, 128);
CloseHandle(h);
DWORD attr = GetFileAttributes(path);
if (attr != INVALID_FILE_ATTRIBUTES) puts("File still exists");
else puts("File is gone");
}

输出:文件不见了

所以“系统增加文件对象的使用计数”绝对是不正确的。而且我认为您反驳了它会增加文件映射对象的使用计数。不知道这是怎么回事,Richter 不会经常出错。本书的勘误表中也没有任何内容。它可能在早期版本的 Windows 中以这种方式工作,不确定,因为我从来没有故意弄错。我们必须坚持 SDK 文档的实际内容:

A shared file mapping object will not be destroyed until all processes that use it close their handles to it by using the CloseHandle function.

关于c++ - Windows 上 MapViewOfFile 的引用计数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33449823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com