mmap

mmap是一个系统调用,它可以将文件直接映射到虚拟空间地址,从而可以像操作内存一样直接操作文件。(普通的文件IO需要先将文件放入页缓存,在page fault时从内核空间拷贝到用户空间,多了一次拷贝的过程)

mmap是一种更加快速的文件IO方法,在lmdb中可以开启mmap来加速数据库读写。

mmap的另一个作用是进程间通信。不同的进程可以通过将相同的文件映射到虚拟地址实现通信。对这块映射的地址的任何改变都可以直接体现在内存中。

 

csapp中的作业mmapcopy,是将任意大小的文件通过mmap输出到stdout

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 #include <unistd.h>
 5 #include <sys/mman.h>
 6 #include <sys/types.h>
 7 #include <sys/stat.h>
 8 #include <fcntl.h>
 9 
10 using namespace std;
11 
12 int main(int argc, char** argv) {
13     if (argc != 2) {
14         cerr <<"Usage: ./mmapcopy file" << endl;
15         return 1;
16     }
17     int fd = open(argv[1], O_RDONLY);
18     if (fd == -1) {
19         cerr <<"open file failed" << endl;
20         return 1;
21     }
22     FILE* f = fopen(argv[1], "r");
23     fseek(f, 0, SEEK_END);
24     int sz = ftell(f);
25 
26     void* s = mmap(NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0);
27     if (s == MAP_FAILED) {
28         cerr << "map file eror" << endl;
29     }
30 
31 
32     write(1, s, sz);
33     return 0;
34 }

 

posted @ 2017-03-10 00:50  zeeroo32  阅读(270)  评论(0编辑  收藏  举报