免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3443 | 回复: 4
打印 上一主题 下一主题

用mmap的时候发生段错误,怎么回事 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-02-08 11:33 |只看该作者 |倒序浏览
  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <fcntl.h>
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. #include <sys/mman.h>

  7. int main()
  8. {
  9.   int fd;
  10.   if ( (fd = open("./file", O_RDWR|O_CREAT, S_IRWXU)) < 0){
  11.     printf("open file wrong!");
  12.     exit(1);
  13.   }

  14.   struct stat file_stat;
  15.   if ( fstat( fd, &file_stat) < 0 )
  16.   {
  17.     printf(" fstat wrong");
  18.     exit(1);
  19.   }



  20.   void *start_fp;
  21.   if( ( start_fp = mmap(NULL, file_stat.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0 )) == MAP_FAILED)
  22.   {
  23.     printf("mmap wrong");
  24.     exit(0);
  25.   }

  26.   snprintf( (char *)start_fp, 4, "test");    //不知道这里为何段错误,有时候还总线错误
  27.   msync( start_fp, file_stat.st_size, MS_ASYNC);

  28.   if ( munmap( start_fp, file_stat.st_size ) < 0 )
  29.   {
  30.     printf("munmap wrong");
  31.     exit(1);
  32.   }
  33. }
复制代码

论坛徽章:
0
2 [报告]
发表于 2010-02-08 12:00 |只看该作者
如果file是新创建的,file_stat.st_size是0,在mmap的话。。。

论坛徽章:
0
3 [报告]
发表于 2010-02-08 12:20 |只看该作者
回复 2# ljysyn


    把它设了100也不行啊

论坛徽章:
0
4 [报告]
发表于 2010-02-08 12:53 |只看该作者
mmap不能改变文件大小的啊,也就是说你的文件必须是存在且有内容

修改的时候也不可以改变文件长短,只能修改内容.

论坛徽章:
0
5 [报告]
发表于 2010-02-08 14:26 |只看该作者
4楼说得对!先用truncate设置文件长度
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP