I’m trying to use CreateFileMapping and OpenFileMapping to share memory between processes. This isn’t working as I want it to – OpenFileMapping returns null and GetLastError is 5 – access denied. Any ideas what I am doing wrong? Name is something like MemoryTest.
Edit:
using CreateFileMapping both times I can read the data written in the other process. The reason this is a problem is that I get Error 183 – memory area already exists. However, it still returns a handle to the existing memory.
var map_handle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(int), name.c_str());
....
var handle = MapViewOfFile(map_handle, FILE_MAP_ALL_ACCESS , 0, 0, 0)
*handle = 10;
UnMapViewOfFile(map_handle);
getchar();
Other process:
var map_handle = OpenFileMapping(PAGE_READWRITE, false, name.c_str())
....
var handle = MapViewOfFile(map_handle, FILE_MAP_ALL_ACCESS , 0, 0, 0) //returns null
var out = *handle;
getchar();
This works for the second process though:
var map_handle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(int), name.c_str());
....
var handle = MapViewOfFile(map_handle, FILE_MAP_ALL_ACCESS , 0, 0, 0) //returns null
var out = *handle;
getchar();
Simple things to be aware of from the very start:
ERROR_ACCESS_DENIED“Access is denied.”ERROR_ALREADY_EXISTS“Cannot create a file when that file already exists.”ERROR_ALREADY_EXISTSis a documented behavior and is an indication of scenario that you do receive handle, but it is a handle to already existing object, not created.The problem with not working
OpenFileMappingis around its first argument: the API function expects values/flags from another enumeration, it takesFILE_MAP_*values and notPAGE_*. Incorrect argument results in failure to open you the mapping you want.