سؤال

I am writing a C program that makes use of mmap system call, running on Linux 3.12 64-bit.

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...

  • Can one process see (read) changed data made by the other process, before or after msync?
  • If update can be seen by the other process - is there a happens-before guarantee made by Linux mmap implementation?
هل كانت مفيدة؟

المحلول

Yes, that's one of the purposes of memory mapping: as a form of "instantaneous IPC".

You must set the MAP_SHARED flag:

If you wish to use shared memory for this purpose, I would consider the shminit()/shmat() APIs instead:

Suggestion: check out Beej's Guide to *nix Interprocess Communication:

And no, if you use the raw mmap() APIs, there's no "before/after guarantee", and you must use some kind of locking (e.g. semaphores) if you wish to read/write data concurrently.

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. 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. 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. 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.

The above is true of any *nix variant, including both Linux and AIX.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top