Linux 中的共享内存备份文件如何以及何时被删除?
我使用 shm_open()
和 mmap()
的组合来为 IPC 创建共享内存段。我想知道的是如何清理备份文件(在我的系统中的 /dev/shm
中,Linux 内核 2.6.31)。
我的问题有三个:
1)进程有责任在终止时取消链接文件吗?如果是这样,如果进程在取消它们的链接之前就终止了怎么办?
2)因为我怀疑#1的答案是“是的,这是程序的责任”,所以我的程序在创建新文件之前删除它注意到的任何陈旧文件是否被认为是“良好做法”,以防以前的实例不干净地死亡?
3)有没有办法让内核在最后一个进程取消映射内存后删除备份文件?我正在考虑类似于 SysV 风格共享内存中的 shmctl(id, IPC_RMID, ...)
的东西。
I am using the combination of shm_open()
and mmap()
to create a shared memory segment for IPC. What I'm wondering is how the backing files (in /dev/shm
in my system, Linux kernel 2.6.31) are cleaned up.
My questions are threefold:
1) Is it the process's responsibility to unlink the files upon termination? If so, what if the process dies before it unlinks them?
2) Since I suspect the answer to #1 is "yes, it's the program's responsibility", is it considered "good practice" for my program to remove any stale files it notices before creating a new one, in case previous instances died uncleanly?
3) Is there a way to ask the kernel to remove the backing file after the last process unmaps the memory? I am thinking of something similar to shmctl(id, IPC_RMID, ...)
in SysV style shared memory.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案如下:
是的,这是程序的责任,尽管可能可以确保清理,请参阅我对 3 的回答。
您可以删除陈旧的文件,您也可以只使用现有的共享内存对象(我假设您无论如何都会重新创建它)。
如果您知道共享部分在最初创建后将不存在其他用户,则可以在映射共享内存后立即使用
shm_unlink
。一旦所有用户取消映射(并关闭)内存区域,该内存区域将被释放。The answers are as following:
Yes, it is the program's responsibility, although it may be possible to ensure cleanup, see my answer to 3.
You could remove the stale files, You could also just use the existing shared memory object (which I assume you were going to recreate anyway).
If you know that no other users for the shared section will exist after it is initially created, you can use
shm_unlink
right after mapping your shared memory. The memory region will be deallocated once all users unmap (and close) it.