Answering things in order:
- It returns a pointer to the location in virtual memory, and virtual memory address space is allocated, but the file is not locked in any way unless you explicitly lock it (also note that locking the memory is not the same as locking the region in the file). An efficient implementation of mmap() is actually only possible from a practical perspective because of paging and virtual memory (otherwise, it would require reading the whole region into memory before the call completes).
- Not exactly, this ties into the next answer though, so I'll cover it there.
- Kind of. What's actually happening in most cases is that mmap() is providing copy-on-write access to that file's data in the page cache. As a result, the usual cache restrictions on data lifetime apply: if the system needs space, pages can be dropped (or flushed to disk if they're dirty) from the cache and need to be faulted in again.
- No, because of how virtual memory works. Each process has its own virtual address space, with its own virtual mappings. Every program that wants to communicate data will have to call mmap() on the same file (or shared memory segment), and they all have to use the
MAP_SHARED
flag.
It's worth noting that mmap() doesn't just work on files, you can also do other things with it such as:
- Directly mapping device memory (if you have sufficient privileges). This is actually used on many embedded systems to avoid the need to write kernel mode drivers for new hardware.
- Map shared memory segments.
- Explicitly map huge pages.
- Allocate memory that you can then call madvise(2) on which in turn lets you do useful things like prevent data from being copied to a child process on fork(2), or mark data for KSM, Linux's memory deduplication feature.
mmap
but you are using itmmap
.