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.