OS可以自动生长一个MMAP备份文件吗?

发布于 2025-01-27 10:49:40 字数 1043 浏览 2 评论 0原文

mmap有很多用途,但是我主要使用mmap以两种方式:

  • mmap读取整个文件
  • mmap以创建共享内存。

在共享内存的情况下,如果我希望它得到文件支持,我会使用ftruncate()来确保文件的大小与我希望mmap 。

我很好奇如果文件大小不匹配会发生什么。 Man页面在这里没有足够的详细信息。

我认为MMAP必须处理此文件的情况。 例如,因为文件的长度不必是页面大小的倍数 而且您可能只想阅读文件的一部分。

在写它的情况下呢?

操作系统可以懒惰地创建文件后的存储吗?

例如,如果我将1GB mmap到空文件。

当我尝试写信时,操作系统会根据需要扩展文件吗?

我的直觉(可能是错误的)是,映射应与文件read()write()呼叫一致。 因此,读取文件末尾的读取将失败 但是,在文件末尾以外的写入将根据需要将其扩展。

实际上,我还希望该页面被标记为脏页,只有在调用msync() munmap()时,才真正写入物理文件。因此,该文件仅在此时扩展。

这个问题和答案,但是建议出现总线错误。

是总是这样的情况,还是仅对于标志的某些组合是正确的? 这里的引擎盖下发生了什么?

这不是我要做的事情,但是假设的用例可能是按需生长的交换的用户空间实现。例如,如果您试图节省磁盘空间。

提出问题的另一种方法是:

在使用ftruncate()使用mmap()之前,是否有必要调用ftruncate()

我特别对Linux感兴趣,但也对Posix的正确性感到好奇。

mmap has many uses but I primarily use mmap in two ways:

  • mmap to read an entire file
  • mmap to create shared memory.

In the case of shared memory if I want it backed by a file I use ftruncate() to make sure the size of the file exactly matches the size of the region I wish to mmap.

I'm curious about what happens if the file sizes does not match.
The man page does not give sufficient detail here.

I think mmap has to handle this for the case of reading a file.
For example, because the length of a file does not have to be a multiple of the page size
and you might only want to read a portion of the file.

What about in the case of writing it?

Can the OS create the file backed storage lazily?

For example if I mmap 1Gb to an empty file.

Will the OS extend the file as necessary when I attempt to write to it?

My intuition (which is likely wrong) is that a mapping should behave consistently with file read() and write() calls.
So a read beyond the end of a file will fail
but a write beyond the end of a file will extend it as required.

In fact, I would also expect the page to be marked as dirty and only actually written to the physical file when msync() or munmap() is called. So the file only be extended at that point.

This question and answer however suggest that a bus error would occur.

Is that always the case or is it true for some combinations of flags only?
What is going on under the hood here?

This is not something I'm trying to do but a hypothetical use case might be a userspace implementation of swap which grows on demand. For example, if you were trying to save disk space.

Another way of posing the question is:

Is it actually necessary to call ftruncate() before using mmap()?

I'm interested in Linux specifically but curious about POSIX correctness as well.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文