mmap映射内存的大小是不是不能超过文件大小?

wangpeng_118 2012-06-08 03:22:34
做了以下实验:
1.文本文件 HELLO.txt 的大小有6个字节;
2.使用mmap成功映射这个文件到内存;mmap( NULL,6, ... )
3.修改mmap返回的指针,程序退出后查看文件,文件内容已成功改变。

我把mmap的第二个参数设置的很大,但是最后文件 HELLO.txt 只有6个字节。
我想问一下,是不是mmap大小不能超过映射文件的大小?

假如我有一个程序是从数据库导出大量数据,经过处理后写入mmap映射的文件,
那我必须预先计算好将要写入的数据大小,否则就写不进去了。
...全文
938 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
wangpeng_118 2012-06-08
  • 打赏
  • 举报
回复
[Quote=引用楼主 的回复:]
做了以下实验:
1.文本文件 HELLO.txt 的大小有6个字节;
2.使用mmap成功映射这个文件到内存;mmap( NULL,6, ... )
3.修改mmap返回的指针,程序退出后查看文件,文件内容已成功改变。

我把mmap的第二个参数设置的很大,但是最后文件 HELLO.txt 只有6个字节。
我想问一下,是不是mmap大小不能超过映射文件的大小?

假如我有一个程序是……
[/Quote]

“We must first grow the file”
谢谢,试验了一下,要用lseek先扩展一下文件。
赵4老师 2012-06-08
  • 打赏
  • 举报
回复
_lseeki64
justkk 2012-06-08
  • 打赏
  • 举报
回复
不能超过

摘自APUE
Since the starting offset of the mapped file is tied to the system's virtual memory page size, what happens if the length of the mapped region isn't a multiple of the page size? Assume that the file size is 12 bytes and that the system's page size is 512 bytes. In this case, the system normally provides a mapped region of 512 bytes, and the final 500 bytes of this region are set to 0. We can modify the final 500 bytes, but any changes we make to them are not reflected in the file. Thus, we cannot append to a file with mmap. We must first grow the file

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧