c++ - c++ - writing to memory mapped file while it is memory-mapped - answerstu - answerstu.com answerstu

c++ - writing to memory mapped file while it is memory-mapped

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

  1. Andrew- Reply

    2019-11-13

    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,

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>