打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
如何将文件里的内容不经过物理内存直接映射到虚拟内存
userphoto

2018.04.06

关注
  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$


                       
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
用mmap()共享内存(转)
mmap把文件映射到内存
Linux 共享内存(POSIX)
mmap函数使用
mmap
@yuanbor:通过ioctl获得块设备的大小
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服