2.3.6 内存映射
内存映射原理
内存映射
(Memory Mapping
)技术是开辟一块与映射磁盘
空间等大的内存空间,操作映射内存
即可自动同步映射磁盘
空间。值得注意的是,在Linux
内存映射实现中,映射内存
必须是页(即4096Bytes
)的倍数,不足4096Bytes
的倍数向上取整倍。- 在
Linux
中,映射内存
位于虚拟内存空间
的共享区
。同时,在内存映射
时,无需对内核
介入与数据缓存而直接写入。因此,内存映射
不仅操作更为方便,在大数据规模时效率上也有一定优势。 内存映射
同样支持匿名模式,这将不需要指定磁盘
文件。
内存映射实现
mmap
、munmap
#include <sys/mman.h>
// map a file or device into memory
// addr:
// Address base of the memory, it's a hint of address to kernel but not exactly the address.
// Usually NULL is given.
// length:
// address bound of the mapping memory in bytes
// usually lseek(fd, 0, SEEK_END) is given
// prot:
// optional:
// PROT_READ:
// read permisson to the mapping memory
// PROT_WRITE:
// write permisson to the mapping memory, PROT_WRITE should given with PROT_READ
// PROT_EXEC:
// execute permisson to the mapping memory
// flags:
// exactly one bellow:
// MAP_SHARED:
// mapping memory can shared with other process
// usually MAP_SHARED is choosing
// MAP_PRIVATE:
// mapping in copy-on-write mode, and can not shared with other process
// optional:
// MAP_ANON (MAP_ANONYMOUS):
// anonymous mapping, not backed by any file
// "fd" should be -1 and "offset" should be 0 if it's chosen.
// fd:
// file descriptor
// offset:
// offset in the file
// ususally 0 is given
// return value:
// return exact address, or -1 for error
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
// unmap a file or device
// addr:
// address base of mapping memory
// length:
// address bound of mapping memory
int munmap(void *addr, size_t length);
// About more
// $ man 2 mmap
推荐阅读
共享内存(Shared Memory)与内存映射技术相仿。但不同的是,内存映射建立了与磁盘空间的同步关系(不考虑匿名内存映射),这意味着内存映射同样需要操作磁盘;而共享内存在物理内存中开辟空间,为不同进程建立相同的虚拟内存映射,无需操作磁盘,效率更高。