linux - 释放共享内存段

标签 linux memory-management ipc shared-memory

我有代码可以用

 int shmId = shmget(key, shmBytes, IPC_CREAT | 0666 );
 shmAddress = (char *) shmat(shmId, NULL, 0);
 /* do some stuff */
 /* detach */
 shmdt(shmAddress);

我的问题是,我是否需要取消分配我通过 shmget 获得的段?或者 shmdt 会处理这个问题吗?

谢谢!

最佳答案

如果您使用的是 Linux,您应该考虑使用 POSIX shared memory system (shm_open, shm_unlink),主要使用标准的POSIX文件API(mmap, ftruncate等)与共享内存区域交互。它也被认为比您正在使用的旧 SYSV 界面更现代。

无论如何,销毁 SYSV 段的方法是在分离段之前使用 shmctl(shmId, IPC_RMID, NULL)。来自 man 2 shmctl :

IPC_RMID

Mark the segment to be destroyed. The segment will only actually be destroyed after the last process detaches it (i.e., when the shm_nattch member of the associated structure shmid_ds is zero). The caller must be the owner or creator, or be privileged. If a segment has been marked for destruction, then the (nonstandard) SHM_DEST flag of the shm_perm.mode field in the associated data structure retrieved by IPC_STAT will be set. The caller must ensure that a segment is eventually destroyed; otherwise its pages that were faulted in will remain in memory or swap.

关于linux - 释放共享内存段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25514599/

相关文章:

c++ - 用于存储大量索引的数据结构,每个索引指向一个集合

c - 使用哪个IPC我可以将文件描述符从一个进程传递到同一台机器上的另一个进程?

java - linux服务器中的服务器套接字代码

linux - shell 脚本已从带有回显输出的 edbplus sql 结果中检索

java 清除内部内存缓存

java - 在 Java 中,变量内存空间是动态分配的还是静态分配的?

linux - 如何使用linux命令删除文本文件中的一部分行

linux - sar %ifutil 和 nicstat %Util 有什么区别?

c - C++ 中的监视器 - Linux

c++ - System V 消息队列问题