【C语言】【unix c】使用mmap将文件映射到进程的虚拟地址空间,然后对内存的操作直接反应到文件中

来源:互联网 发布:cydia数据库错误 编辑:程序博客网 时间:2024/06/05 14:45
二、使用mmap将文件映射到进程的虚拟地址空间,然后对内存的操作直接反应到文件中    将文件hello映射到内存,在内存中对文件的内容进行修改,改变其内容(mmap_file.c)        #include <stdio.h>        #include <p_file.h>        #include <sys/mman.h>        int main(void) {            int prot = PROT_READ | PROT_WRITE;            int flags = MAP_SHARED; //对映射区域的更新给其他进程看,也同步到下层的更新             int fd = open("hello", O_RDWR);//以读写方式打开文件            if(fd == -1) {            perror("open");            return -1;            }            void *p = mmap(NULL, 8, prot, flags, fd, 0);//从文件开始映射8个字节到,flags为MAP_ANONYMOUS时不进行文件映射            if(p == MAP_FAILED) {            perror("mmap");            return -1;            }            int *q = (int *)p;            q[0] = 0x30313233;            //*((int *)p) = 0x30313233;            close(fd);            munmap(p, 8);            return 0;        }    命令: tarena@ubuntu:~/day/day28$ a.out     命令: tarena@ubuntu:~/day/day28$ od -tx1 -tc hello     结果: 0000000  33  32  31  30  6f  0a              3   2   1   0   o  \n           0000006    分析:int在内存中占4个字节          0x30313233在内存中的保存是            00110011 00110010 00110001 00110000               33        32      31        30        存文件后转为字符显示               3         2        1         0
阅读全文
0 0
原创粉丝点击