1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<sys/mman.h>
4 #include<unistd.h>
5 #include<fcntl.h>
6 #include<string.h>
7
8 int main()
9 {
10 int fd = open("mytest.txt",O_RDWR | O_CREAT,0644);
11 if(fd == -1 )
12 {
13 perror("open error");
14 exit(1);
15 }
16
17 int len = ftruncate(fd,4);
18 if(len == -1)
19 {
20 perror("ftruncate error");
21 exit(1);
22 }
23 char * p=NULL;
24 p = mmap(NULL,4,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
25 if( p == MAP_FAILED )
26 {
27 perror("mmap error");
28 exit(1);
29 }
30 strcpy(p,"abvc\n");
31
32 int ret = munmap(p,4);
33 if(ret == -1)
34 {
35 perror("mummap error");
36 exit(1);
37 }
38 close(fd);
39 return 0;
40 }
来源:CSDN
作者:YanWenCheng_
链接:https://blog.csdn.net/YanWenCheng_/article/details/103935650