3
votes

I'm trying to use a memory-mapped file under windows (using CreateFile/CreateFileMapping/MapViewOfFile functions), and I'm currently specifying FILE_SHARE_READ and FILE_SHARE_WRITE when calling CREATE_FILE. However, this is locking the file from being using by other processes.

What I want is to memory-map a snapshot of the file at the time I call CreateFileMapping or MapViewOfFile, so that I don't see any changes (writes or deletes) made to the file by other processes. Sort of like copy-on-write, but other processes are doing the write. Can I do this using memory-mapped files on windows?

1
Out of curiosity, how big is this file?Matteo Italia
In this case, unless the conditions are very peculiar, I probably wouldn't bother and just allocate the needed memory and read the file into it. (Nonetheless I gave my +1 because it's an interesting question)Matteo Italia

1 Answers

3
votes

That's just not how memory mapped files work. Windows puts a hard lock on the file so that nobody can change its content and make it different from the pages mapped into RAM. Those pages in RAM are shared between all processes that created a view on the file. There is no 'tear off' option.

You could simply map the file and make a copy of the bytes in the view. Some synchronization with the other processes would typically be required.