0
votes

I need a mechanism to share memory between some threads (usually in the same process, but sometimes not).

This code, which seems very basic, fails with error 5 (access denied) on MapViewOfFile:

HANDLE hSharedMemCreated = CreateFileMapping(
    INVALID_HANDLE_VALUE,    // use paging file
    NULL,                    // default security
    PAGE_READWRITE,          // read/write access
    0,                       // maximum object size (high-order DWORD)
    10000,                // maximum object size (low-order DWORD)
    "testFileMapping");                 // name of mapping object
HANDLE hSharedMemOpened = OpenFileMapping(
    PAGE_READWRITE,          // read/write access
    FALSE,
    "testFileMapping"
);
void* location = MapViewOfFile(
    hSharedMemOpened,   // handle to map object
    FILE_MAP_ALL_ACCESS, // read/write permission
    0,
    0,
    10);
  • MapViewOfFile succeeds with the opened handle hSharedMemOpened with permission FILE_MAP_READ.
  • MapViewOfFile succeeds with the created handle hSharedMemCreated with permission FILE_MAP_ALL_ACCESS.
  • MapViewOfFile fails with the opened handle hSharedMemOpened with permission FILE_MAP_ALL_ACCESS.
1
In MapViewOfFile(), FILE_MAP_ALL_ACCESS is equivalent to FILE_MAP_WRITE. Are you SURE you are opening a mapping object that was created with write permissions? Are you calling CreateFileMapping() and OpenFileMapping() in separate processes? If not, you shouldn't be using them together at all, let alone giving the mapping object a name.Remy Lebeau
PAGE_READWRITE is not a valid argument for OpenFileMapping(). You probably want FILE_MAP_ALL_ACCESS instead.Jonathan Potter

1 Answers

1
votes

The answer is in the comments:

PAGE_READWRITE is not a valid argument for OpenFileMapping(). You probably want FILE_MAP_ALL_ACCESS instead.