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/