Search code examples
cwindowswinapiiomemory-mapped-files

What is the correct way of using CreateFileMapping and MapViewOfFile if I intend to access multiple parts of a file by multiple processes?


I am writing a component in C which will be used by several different processes all accessing the same file.

Each process will be accessing different parts of the file at the same time, mostly for reading but also for writing.

I am trying to figure out if the correct way is:

Opition A: For each process to call CreateFileMapping once for the entire file and then use MapViewOfFile multiple times on different sections to access the parts it needs, meaning if I have 10 sections I wish to access I will call CreateFileMapping once for the whole file, end to end, and then MapViewOfFile 10 times, once for each part of the file.

OR

Option B: For each process to call CreateFileMapping & MapViewOfFile on each specific section it wishes to access, meaning if I have 10 sections I wish to access I will call CreateFileMapping & MapViewOfFile each 10 times.

Thanks!


Solution

  • You will definitely need to call CreateFileMapping and MapViewOfFile at least once per process in order to access the data. However you don't need to call them more than that once. Of course, if the mapping themselves are large, you might want to unmap and remap to save virtual address space, but if the amount of data is not that large you can skip this.

    Having mapped your file mapping, your process sees the data directly. Reading and writing operations occur instantly and in order to serialize access and prevent from thread racing conditions you need to use Interprocess Communication, such as semaphores.

    Something you might want to read and study sample code: Shared Memory. Also try a google search for MapViewOfFile + WaitForMultipleObjects for more information.