1. Mmap
Mmap can map a portion of a disk file directly to memory, so that the location of the file directly has a corresponding memory address, read and write to the file can be directly with the pointer without the need for the Read/write function.
Shared memory Exchange data, not switch the power level, fast.
Mmap Cons: 1) consumes memory, fragmentation. 2) ordinary documents.
Pros: 1) Map speed is fast. 2) can be atomic access to any byte, do not worry about offset.
#include <sys/mman.h>
void *mmap (void *addr, size_t len, int prot, int flag, int fd, off_t off);
int Munmap (void *addr, size_t len);
Addr:null, the kernel maps itself to the appropriate address in the process address space.
Len: No more than file length, otherwise bus error.
Prot:prot_read,prot_write, Prot_none, prot_exec
Flag:map_shared, Map_private, Map_anon
When the map_shared map area is unmap, the modification writes back to the disk file.
Map_private does not write back the disk file.
Map_anon (anonymous zone) pure memory area, not dependent on any files.
Off: File start offset.
The mmap mapped memory space is between the heap and the stack (user space).
Successful return of spatial address, failed return map_failed (= = (void *)-1)
Prot_exec requires FD to be readable rdonly,prot_write requires FD to be o_rdwr.
Map writes data to disk directly from user space while writing back to disk, saving write-back time.
Regular copies require copying data from the user space to the kernel, and then the kernel writes back to the disk.
Anonymous mappings:
Char *p = mmap (NULL, prot_write| Prot_read, Map_shared,-1, 0);
FD = 1 represents a file-independent.
When you apply Mmap (), you can close the FD when the mmap () call is complete.
FD shutdown does not affect the mapping that the file has established, and it can still read and write to the file.
You can use the Strace command to execute a program that tracks the parameters and return values of all system calls that are used during program execution.
Memory-Mapped Files mmap