Deleting shared memory segment with shmctl
Your first reasoning is correct. The shared segment will exists until both: it is marked with IPC_RMID
and last process detaches.
The purpose of the second fragment is to remind you, that in a solution using shared memory you need to have some process mark it for destruction or it will remain in memory/swap forever. It might be good idea to use IPC_RMID
immediately after creating segment.
If you are not sure you have successfully released memory, you can use ipcs
program to list remaining segments.
Related videos on Youtube
MrHappyAsthma
Updated on October 19, 2022Comments
-
MrHappyAsthma over 1 year
I am confused by the linux
man pages
forshmctl()
. I use the following command:shmctl (id , IPC_RMID , 0)
to remove a shared segment. Theman pages
seem to contradict itself about the memory's lifetime.The man pages state:
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.
If I am correct, I believe this means if you have two processes that both attach to shared memory, (Lets call them
Process1
andProcess2
),Process1
could create the shared memory, attach, detach, destroy the shared memory, and ultimately terminate. Then the memory will still exist untilProcess2
also detaches.Is this correct?
Secondly, what does this statement in the
man pages
mean:The caller must ensure that a segment is eventually destroyed; otherwise its pages that were faulted in will remain in memory or swap.
This makes it seem like
Process1
, since it marked the segment for deletion, would need to block until all other processes are detached in order to ensure the memory gets deleted. But this seems to contradict the above statement. I also have no idea how this would be done (if it is supposed to be done), so if that is the case, could you also explain how I would go about this.