writing to memory mapped file while it is memory-mapped


Keywords:c++ 


Question: 

I have memory mapped a file on disk as follow:

 const wchar_t fileName[] = L"temp.txt";
 HANDLE h = CreateFile(fileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
 HANDLE fileMap = CreateFileMapping(h, NULL, PAGE_READWRITE, 0x0, 1024, NULL);
 char *ptr = (char *)MapViewOfFile(fileMap, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0, 1024)

Is it possible to write to the same file by another process while it is memory mapped?

FILE *fp = fopen("temp.txt", "w+"); if(NULL == fp) printf("Failed to open\n");

Above code always prints 'Failed to open' if the file is memory mapped.


1 Answer: 

The answer for a coherent shared use is simply :yes ,except for remote files. (see documentations of CreateFileMapping and/or MapViewOfFile).

For shared use you must however open the file (CreateFile) in a shared-mode (which you didn't specify). I don't know in which share-mode fopen operates ,but I suspect your fopen fails because of the missing share-mode with CreateFile. If fopen still fails when using a shared-mode you should use CreateFile instead,