Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6086899
  • 博文数量: 2759
  • 博客积分: 1021
  • 博客等级: 中士
  • 技术积分: 4091
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-11 14:14
文章分类

全部博文(2759)

文章存档

2019年(1)

2017年(84)

2016年(196)

2015年(204)

2014年(636)

2013年(1176)

2012年(463)

分类:

2012-11-08 12:58:11


点击(此处)折叠或打开

  1. ////本程序的功能是把一个文件映射到
  2. //内存然后再把内存中的东西利用write函数给输出到标准输出
  3. //最后利用munmap解除内存映射
  4. #include<stdio.h>
  5. #include<sys/mman.h>
  6. #include<fcntl.h>
  7. #include<unistd.h>
  8. int main(int argc,char *argv[])
  9. {
  10.     if(argc!=4)
  11.     {
  12.          write(STDOUT_FILENO,"hello\n",6);
  13.          printf("usage:%s \n",argv[0]);
  14.          return 1;
  15.     }
  16.     char *filename=argv[1];//第二个参数表示文件名
  17.     printf("the file name to be mapped is :%s\n",filename);
  18.     int fd=open(filename,O_RDONLY);
  19.     int offset=atoi(argv[2]);//第三个参数标识要映射时的开始偏移量
  20.     printf("start offset of file to be mapped is :%d\n",offset);
  21.     printf("page size is %ld\n",sysconf(_SC_PAGE_SIZE));
  22.     int realOffset=offset&~(sysconf(_SC_PAGE_SIZE)-1);
  23.     printf("real start offset of file to be mapped is %d\n",realOffset);
  24.     int length=atoi(argv[3]);//要映射的文件的长度
  25.     printf("the length to be map is :%d\n",length);
  26.     int reallen=length+offset-realOffset;//实际映射的长度
  27.     printf("the real length to be map is %d\n",reallen);
  28.     char *addr=mmap(NULL,reallen,PROT_READ,MAP_PRIVATE,fd,realOffset);//有关该函数我们可以使用 //man命令去查看
  29.     close(fd);
  30.     write(STDOUT_FILENO,addr,reallen);/*输出到标准输出*/
  31.     munmap(addr,reallen);//解除内存映射
  32.     printf("\n");

  33.     return 0;
  34.     
  35. }

阅读(873) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~