对于mmap,实际上是创建了/或者合并 一个新的线性地址区间
测试代码如下:
不调用mmap:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
int main(){
char *bufp;
int fd;
struct stat stat;
fd = open("1.txt", O_RDONLY, 0);
fstat(fd,&stat);
//bufp = mmap(NULL, stat.st_size, PROT_READ,MAP_PRIVATE, fd, 0);
while(1){
}
return 0;
}
调用mmap映射磁盘上的1.txt文件:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
int main(){
char *bufp;
int fd;
struct stat stat;
fd = open("1.txt", O_RDONLY, 0);
fstat(fd,&stat);
bufp = mmap(NULL, stat.st_size, PROT_READ,MAP_PRIVATE, fd, 0);
while(1){
}
return 0;
}
前后使用pmap显示如下:
pmap 24731
24731: ./newprog
0000000000400000 4K r-x-- newprog
000000000041f000 4K r---- newprog
0000000000420000 4K rw--- newprog
0000ffffa68c2000 1428K r-x-- libc-2.28.so
0000ffffa6a27000 92K ----- libc-2.28.so
0000ffffa6a3e000 16K r---- libc-2.28.so
0000ffffa6a42000 8K rw--- libc-2.28.so
0000ffffa6a44000 16K rw--- [ anon ]
0000ffffa6a48000 128K r-x-- ld-2.28.so
0000ffffa6a79000 8K rw--- [ anon ]
0000ffffa6a85000 4K r---- [ anon ]
0000ffffa6a86000 4K r-x-- [ anon ]
0000ffffa6a87000 4K r---- ld-2.28.so
0000ffffa6a88000 4K rw--- ld-2.28.so
0000ffffa6a89000 4K rw--- [ anon ]
0000fffffd9ce000 136K rw--- [ stack ]
total 1864K
0000000000400000 4K r-x-- newprog
000000000041f000 4K r---- newprog
0000000000420000 4K rw--- newprog
0000ffffa002e000 1428K r-x-- libc-2.28.so
0000ffffa0193000 92K ----- libc-2.28.so
0000ffffa01aa000 16K r---- libc-2.28.so
0000ffffa01ae000 8K rw--- libc-2.28.so
0000ffffa01b0000 16K rw--- [ anon ]
0000ffffa01b4000 128K r-x-- ld-2.28.so
0000ffffa01e5000 8K rw--- [ anon ]
0000ffffa01f0000 4K r---- 1.txt
0000ffffa01f1000 4K r---- [ anon ]
0000ffffa01f2000 4K r-x-- [ anon ]
0000ffffa01f3000 4K r---- ld-2.28.so
0000ffffa01f4000 4K rw--- ld-2.28.so
0000ffffa01f5000 4K rw--- [ anon ]
0000ffffef991000 136K rw--- [ stack ]
total 1868K
可见地址空间里面多了一个内存区域---4K的页映射了1.txt文件