linux - 对共享内存对象进行 ben mmap 后,ftruncate 是否安全?

标签 linux memory-management posix shared-memory

  • shm_open()
  • mmap() 具有预定义的大长度
  • fork()(多次)
  • ftruncate() 随意

这样做的目的是确保 fork() 生成的每个进程在同一地址都有一个共享段。然而,我不想让 RAM 一直忙碌,而是动态调整它的大小(大小跨越 0 - 大 length)。

这行得通吗?有UB吗?

最佳答案

不,没关系。您可以随时截断底层文件,但如果您访问超出文件范围的内存,您可能会收到 SIGBUS。因此,您需要格外小心,不要触及超过文件当前长度的内存(或捕​​获 SIGBUS 并处理它)。

来自 man 2 mmap:

Use of a mapped region can result in these signals:

SIGBUS Attempted access to a portion of the buffer that does not correspond to the file (for example, beyond the end of the file, including the case where another process has truncated the file).

关于linux - 对共享内存对象进行 ben mmap 后,ftruncate 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13126167/

相关文章:

linux - 在内核回溯中,单下划线是什么意思

Objective-C 2.0;分配属性(property);内存泄漏?

iphone - 我要释放多少次已分配或保留的对象?

c - 内核如何处理对共享映射的并发访问?

c++ - 带有 GNU/Linux 代码生成工具的 UML

c - perror() 和 printf() 之间的区别

linux - 为什么通过 Ubuntu 软件中心安装 debian 软件包时 postinst 脚本不执行命令?

c# - 如何使用 C# 测量内存使用情况(就像我们在 Java 中所做的那样)?

c - 为什么这个基准代码使用如此高的 CPU?

c++ - 如果 send() 返回 x 个字节,recv() 是否在一次调用中获得相同数量的字节?