gpt4 book ai didi

linux - 释放共享内存段

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:53:21 26 4
gpt4 key购买 nike

我有代码可以用

 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com