1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <fcntl.h>
4 #include <sys/stat.h>
5 #include <unistd.h>
6 #include <sys/mman.h>
7 int main(void){
8 int fd = 0;
9 fd = open("hello.c",O_RDWR);
//打开hello.c文件,读写模式 10 if(fd == -1){
11 perror("open");
12 return 1;
13
14 }
15 //将文件爱你映射到虚拟地址
16 void *p = mmap(NULL,6,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
//按位或
17 if(p == MAP_FAILED){
//映射错误
18 perror("mmap");
19 return 2;
20 }
21 int *str = (int *)p;
22 str[0] = 0x33323130;
//十六进制的33、32、31、30分别是一个字节,3是四比特位
23
24 munmap(p,6);
25 close(fd);
26
27
28
29
30 return 0;
31 }
这是hello.c文件的内容
tarena@ubuntu:~/uc/day05$ od -tx1 -tc hello.c
//可以查看文件里的内容和字符的ASCII值
0000000 68 65 6c 6c 6f 20 77 6f 72 6c 64 0a
h e l l o w o r l d \n
0000014
tarena@ubuntu:~/uc/day05$
在映射到虚拟内存之后
tarena@ubuntu:~/uc/day05$ gcc mapfile.c
tarena@ubuntu:~/uc/day05$ od -tx1 -tc hello.c
0000000 68 65 6c 6c 6f 20 77 6f 72 6c 64 0a
h e l l o w o r l d \n
0000014
tarena@ubuntu:~/uc/day05$ ./a.out
tarena@ubuntu:~/uc/day05$ od -tx1 -tc hello.c
0000000 30 31 32 33 6f 20 77 6f 72 6c 64 0a
0 1 2 3 o w o r l d \n
0000014
tarena@ubuntu:~/uc/day05$
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。