1*cf7f801eSMemoryShore #include <sys/mman.h>
2*cf7f801eSMemoryShore #include <sys/types.h>
3*cf7f801eSMemoryShore #include <sys/stat.h>
4*cf7f801eSMemoryShore #include <fcntl.h>
5*cf7f801eSMemoryShore #include <unistd.h>
6*cf7f801eSMemoryShore #include <stdio.h>
7*cf7f801eSMemoryShore #include <stdlib.h>
8*cf7f801eSMemoryShore
main()9*cf7f801eSMemoryShore int main()
10*cf7f801eSMemoryShore {
11*cf7f801eSMemoryShore // 打开文件
12*cf7f801eSMemoryShore int fd = open("example.txt", O_RDWR | O_CREAT | O_TRUNC, 0777);
13*cf7f801eSMemoryShore
14*cf7f801eSMemoryShore if (fd == -1)
15*cf7f801eSMemoryShore {
16*cf7f801eSMemoryShore perror("open");
17*cf7f801eSMemoryShore exit(EXIT_FAILURE);
18*cf7f801eSMemoryShore }
19*cf7f801eSMemoryShore
20*cf7f801eSMemoryShore write(fd, "HelloWorld!", 11);
21*cf7f801eSMemoryShore char buf[12];
22*cf7f801eSMemoryShore buf[11] = '\0';
23*cf7f801eSMemoryShore close(fd);
24*cf7f801eSMemoryShore
25*cf7f801eSMemoryShore fd = open("example.txt", O_RDWR);
26*cf7f801eSMemoryShore read(fd, buf, 11);
27*cf7f801eSMemoryShore printf("File content: %s\n", buf);
28*cf7f801eSMemoryShore
29*cf7f801eSMemoryShore // 将文件映射到内存
30*cf7f801eSMemoryShore void *map = mmap(NULL, 11, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
31*cf7f801eSMemoryShore if (map == MAP_FAILED)
32*cf7f801eSMemoryShore {
33*cf7f801eSMemoryShore perror("mmap");
34*cf7f801eSMemoryShore close(fd);
35*cf7f801eSMemoryShore exit(EXIT_FAILURE);
36*cf7f801eSMemoryShore }
37*cf7f801eSMemoryShore printf("mmap address: %p\n", map);
38*cf7f801eSMemoryShore
39*cf7f801eSMemoryShore // 关闭文件描述符
40*cf7f801eSMemoryShore // close(fd);
41*cf7f801eSMemoryShore
42*cf7f801eSMemoryShore // 访问和修改文件内容
43*cf7f801eSMemoryShore char *fileContent = (char *)map;
44*cf7f801eSMemoryShore printf("change 'H' to 'G'\n");
45*cf7f801eSMemoryShore fileContent[0] = 'G'; // 修改第一个字符为 'G'
46*cf7f801eSMemoryShore printf("mmap content: %s\n", fileContent);
47*cf7f801eSMemoryShore
48*cf7f801eSMemoryShore // 解除映射
49*cf7f801eSMemoryShore printf("unmap\n");
50*cf7f801eSMemoryShore if (munmap(map, 11) == -1)
51*cf7f801eSMemoryShore {
52*cf7f801eSMemoryShore perror("munmap");
53*cf7f801eSMemoryShore exit(EXIT_FAILURE);
54*cf7f801eSMemoryShore }
55*cf7f801eSMemoryShore
56*cf7f801eSMemoryShore fd = open("example.txt", O_RDWR);
57*cf7f801eSMemoryShore read(fd, buf, 11);
58*cf7f801eSMemoryShore printf("File content: %s\n", buf);
59*cf7f801eSMemoryShore
60*cf7f801eSMemoryShore return 0;
61*cf7f801eSMemoryShore }
62