Linux 高并发学习笔记 - 内存映射

2.3.6 内存映射

Linux 高并发学习笔记 - 笔记索引

内存映射原理
  • 内存映射Memory Mapping)技术是开辟一块与映射磁盘空间等大的内存空间,操作映射内存即可自动同步映射磁盘空间。值得注意的是,在Linux内存映射实现中,映射内存必须是页(即4096Bytes)的倍数,不足4096Bytes的倍数向上取整倍。
  • Linux中,映射内存位于虚拟内存空间共享区。同时,在内存映射时,无需对内核介入与数据缓存而直接写入。因此,内存映射不仅操作更为方便,在大数据规模时效率上也有一定优势。
  • 内存映射同样支持匿名模式,这将不需要指定磁盘文件。
内存映射实现
  • mmapmunmap
#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
推荐阅读

Linux 高并发学习笔记 - 共享内存

共享内存(Shared Memory)与内存映射技术相仿。但不同的是,内存映射建立了与磁盘空间的同步关系(不考虑匿名内存映射),这意味着内存映射同样需要操作磁盘;而共享内存在物理内存中开辟空间,为不同进程建立相同的虚拟内存映射,无需操作磁盘,效率更高。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值