如果我打算通过多个进程访问文件的多个部分,使用 CreateFileMapping 和 MapViewOfFile 的正确方法是什么?
我正在用 C 编写一个组件,该组件将由多个访问同一文件的不同进程使用。
每个进程将同时访问文件的不同部分,主要用于读取,但也用于写入。
我试图找出正确的方法是否是:
选项A: 对于每个进程,为整个文件调用一次 CreateFileMapping,然后在不同的部分多次使用 MapViewOfFile 来访问它需要的部分,这意味着如果我希望访问 10 个部分,我将为整个文件调用一次 CreateFileMapping,端到端,然后 MapViewOfFile 10 次,文件的每个部分一次。
或
选项 B: 对于每个进程调用CreateFileMapping& MapViewOfFile 在它希望访问的每个特定部分上,这意味着如果我希望访问 10 个部分,我将调用 CreateFileMapping & MapViewOfFile各10次。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您肯定需要为每个进程至少调用一次
CreateFileMapping
和MapViewOfFile
才能访问数据。不过,您无需多次致电他们。当然,如果映射本身很大,您可能需要取消映射并重新映射以节省虚拟地址空间,但如果数据量不是那么大,您可以跳过此操作。映射文件映射后,您的进程可以直接看到数据。读取和写入操作会立即发生,为了序列化访问并防止线程争用情况,您需要使用 进程间通信,例如信号量。
您可能想要阅读和研究示例代码:共享内存。另请尝试在 Google 上搜索
MapViewOfFile
+WaitForMultipleObjects
了解更多信息。
You will definitely need to call
CreateFileMapping
andMapViewOfFile
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.