[英]What happens when two processes write to same portion of a mmaped file?
I am writing a C program that makes use of mmap
system call, running on Linux 3.12 64-bit. 我正在编写一个使用mmap
系统调用的C程序,该程序在64位Linux 3.12上运行。
If I have two processes mmaping the same region of a disk file with read/write access, and then modify the region content from both processes at the same time... 如果我有两个进程使用读/写访问权限映射磁盘文件的同一区域,然后同时修改两个进程的区域内容...
Yes, that's one of the purposes of memory mapping: as a form of "instantaneous IPC". 是的,这就是内存映射的目的之一:作为“即时IPC”的一种形式。
You must set the MAP_SHARED flag: 您必须设置MAP_SHARED标志:
If you wish to use shared memory for this purpose, I would consider the shminit()/shmat() APIs instead: 如果您希望为此目的使用共享内存,则可以考虑使用shminit()/ shmat()API:
Suggestion: check out Beej's Guide to *nix Interprocess Communication: 建议:查看Beej的* nix进程间通信指南:
And no, if you use the raw mmap() APIs, there's no "before/after guarantee", and you must use some kind of locking (eg semaphores) if you wish to read/write data concurrently. 不,如果您使用原始的mmap()API,则没有“之前/之后保证”,并且如果您希望同时读取/写入数据,则必须使用某种锁定方式(例如信号量)。
Also, from Understanding Memory Mapping : 另外,从了解内存映射 :
Both the mmap and shmat services provide the capability for multiple processes to map the same region of an object such that they share addressability to that object. mmap和shmat服务都为多个进程提供了映射对象同一区域的功能,以便它们共享对该对象的可寻址性。 However, the mmap subroutine extends this capability beyond that provided by the shmat subroutine by allowing a relatively unlimited number of such mappings to be established. 但是,mmap子例程通过允许建立相对不受限制的此类映射,从而将这种功能扩展到shmat子例程所提供的功能之外。 While this capability increases the number of mappings supported per file object or memory segment, it can prove inefficient for applications in which many processes map the same file data into their address space. 尽管此功能增加了每个文件对象或内存段支持的映射数量,但对于许多进程将同一文件数据映射到其地址空间的应用程序来说,效率可能低下。
The mmap subroutine provides a unique object address for each process that maps to an object. mmap子例程为每个映射到对象的进程提供唯一的对象地址。 The software accomplishes this by providing each process with a unique virtual address, known as an alias. 该软件通过为每个进程提供唯一的虚拟地址(称为别名)来实现此目的。 The shmat subroutine allows processes to share the addresses of the mapped objects. shmat子例程允许进程共享映射对象的地址。
The above is true of any *nix variant, including both Linux and AIX. 以上适用于所有* nix变体,包括Linux和AIX。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.