0

I'm studying Memory Mapping on Windows and wrote the following piece code (I omitted error handling from the copy for the sake of readability):

HANDLE file_h = CreateFile(filename, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

HANDLE map_h = CreateFileMapping(file_h, NULL, PAGE_READWRITE, 0, lengthOfFile + padding, NULL);

char * map;
map = MapViewOfFile(map_h, FILE_MAP_COPY, 0, 0, lengthOfFile + padding);

Where lengthOfFile is the length of the file I previously calculated this way (for some reasons that are unrelevant to this case):

FILE * file;
file = fopen(filename,"rb");
fseek(file, 0, SEEK_END);
int lengthOfFile = ftell(file);
fseek(file, 0, SEEK_SET);
int last = (lengthOfFile % 4);
int n_pack = (int)(lengthOfFile / 4);
int padding = 4 - last;

And padding is some additional length I needed to add (you may figure out why by reading the code above).

After that, I perform some operations with the memory mapped file which involve its modification and the dispatch of its new value to another function.

How can I make it so that when I close both the file_h and map_h handles the source file (filename) stays unaltered (right now, as soon as I close its handle it gets modified because of that additional padding which apparently gets "flushed" to the source file right after its handle is closed) ?

I tried using the PAGE_WRITECOPY flag alongside the PAGE_READWRITE (which is needed to modify the content of the memory mapped file) one, but the CreateFileMapping function fails returning a ERROR_INVALID_PARAMETER (87) error.

In other words, I need to achieve the same behavior I managed to get in Unix using: mmap(0,lengthOfFile + padding,PROT_READ | PROT_WRITE, **MAP_PRIVATE**,fileno(file),0); I guess the key point is the MAP_PRIVATE attribute.

Kron
  • 75
  • 7
  • There is no equivalent of that flag. A basic workaround is to pass INVALID_HANDLE_VALUE as the first argument so the memory is backed by the paging file and can't update the actual file. You'll have to fread() the file into the view yourself. – Hans Passant Jun 21 '18 at 21:36
  • Is there really no other way to prevent the modification of the source file in Windows? It's not important if I don't get the exactly same result as I get with MAP_PRIVATE. – Kron Jun 22 '18 at 07:41
  • Perhaps try `FILE_MAP_COPY` (alone) with **`PAGE_WRITECOPY`**? See https://stackoverflow.com/questions/55018806/copy-on-write-file-mapping-on-windows#comment96793206_55018806 – Glenn Slayden May 28 '20 at 00:10

0 Answers0