MapViewOfFile reference counting issue on Windows

It seems to MapViewOfFileincrease the reference count of the file mapping kernel object.

Quote from the MSDN description MapViewOfFile:

The displayed views of the file association object support internal references to the object and the file association object does not close until all references to it have been issued. Therefore, in order to completely close the file object mapping, the application must disable all associated file representations displaying the object by calling UnmapViewOfFileand closing the file mapping Object, calling CloseHandle. These functions can be called in any order.

Also, from Windows via C / C ++, 5th Edition:

The previous code shows the "expected" method of manipulating memory mapped files. However, what it does not show is that the system increases the amount of use of the file object and the file mapping object when you call MapViewOfFile...

Despite this, my actual test shows the opposite. I am using Visual Studio 2015 for Windows 10 64-bit. The testing program is as follows:

#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
}

Failure OpenFileMappingwith last error ERROR_FILE_NOT_FOUND. When I remove the call CloseHandle, everything will be fine. This means that the call CloseHandleremoves the last reference count on the file association kernel object and destroys it. This, in turn, implies that it MapViewOfFiledoes not actually increase the reference count of the object.

, , MapViewOfFile .

+4
1

, :

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

:

, " ", . , , . , , . . , Windows, , . , SDK:

, , , CloseHandle.

+3

Source: https://habr.com/ru/post/1613943/


All Articles