博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mmap from man
阅读量:6174 次
发布时间:2019-06-21

本文共 2011 字,大约阅读时间需要 6 分钟。

1:  /*
2:  author:justinzhang
3:  email:uestczhangchao@gmail.com
4:  time:2012-8-22 16:23:08
5:  desc: mmap()practice from man mmap
6:  */
7:  #include 
8:  #include 
9:  #include 
10:  #include 
11:  #include 
12:  #include 
13:   
14:  #define handle_error(msg)\
15:  do { perror(msg); exit(EXIT_FAILURE); } while(0)
16:  int
17:  main(int argc, char *argv[])
18:  {
19:      char *addr;
20:      int fd;
21:      struct stat sb;
22:      off_t offset, pa_offset;
23:      size_t length;
24:      ssize_t s;
25:      if(argc <3 || argc > 4)
26:      {
27:          fprintf(stderr, "%s file offset [length]\n",argv[0]);
28:      exit(EXIT_FAILURE);
29:      }
30:      fd = open(argv[1],O_RDONLY);
31:      if(fd == -1)
32:      {
33:          handle_error("open");
34:      }
35:      if(fstat(fd, &sb) == -1)/*to obtain file size*/
36:      {
37:          handle_error("fstat");
38:      }
39:      offset = atoi(argv[2]);
40:      pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE)-1);
41:         /*offset for mmap() must be page aligned*/
42:      if( offset >= sb.st_size)
43:      {
44:          fprintf(stderr, "offset is past end of file\n");
45:      exit(EXIT_FAILURE);
46:      }
47:      if(argc == 4)
48:      {
49:          length = atoi(argv[3]);
50:      if(offset + length > sb.st_size)
51:          length = sb.st_size - offset;
52:          /*can't display bytes past end of file*/
53:      }else {
/*No length arg ==> display to end of file*/
54:          length = sb.st_size - offset;
55:      }
56:      addr = mmap(NULL, length + offset - pa_offset, PROT_READ,MAP_PRIVATE, fd
57:                  ,pa_offset);
58:      if(addr == MAP_FAILED)
59:          handle_error("mmap");
60:      s = write(STDOUT_FILENO, addr + offset - pa_offset, length);
61:      if (s != length)
62:      {
63:          if (s == -1)
64:          handle_error("write");
65:      fprintf(stderr, "partial write");
66:      exit(EXIT_FAILURE);
67:      }
68:      exit(EXIT_SUCCESS);
69:  }
 

转载地址:http://vimba.baihongyu.com/

你可能感兴趣的文章
NASA制做模拟系外行星环境 发现了热木星大气不透明的原因
查看>>
SVN用法
查看>>
Flutter滚动, 中间显示整图, 前后露出部分图
查看>>
JavaScript 复习之 对象的继承
查看>>
openinstall免费服务对App推广有哪些作用?
查看>>
基于Docker的微服务CI CD流水线
查看>>
Linux微职位学习笔记-终端
查看>>
自己写了一个友盟推送的util
查看>>
Mapreduce 扫描hbase表建立solr索引
查看>>
RHEL 5.8 yum本地源
查看>>
Teams 新功能更新【五月底】Busy on Busy 忙线音
查看>>
orzdba安装与使用
查看>>
二叉搜索树的插入叶子结点的递归实现方法
查看>>
通过nginx配置不同二级域名代理多个系统
查看>>
linux基础篇-23,文件系统管理
查看>>
keepalived+nginx高可用配置
查看>>
node.js爬虫爬取电影天堂,实现电视剧批量下载。
查看>>
Ubuntu 18.04.1 LTS下部署FastDFS 5.11+Nginx 1.14.0
查看>>
PHP 运行方式(PHP SAPI介绍)
查看>>
puppet学习之puppet证书验证
查看>>