Deleting shared memory segment with shmctl

14,855

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.

Share:
14,855

Related videos on Youtube

MrHappyAsthma
Author by

MrHappyAsthma

Updated on October 19, 2022

Comments

  • MrHappyAsthma
    MrHappyAsthma over 1 year

    I am confused by the linux man pages for shmctl(). I use the following command: shmctl (id , IPC_RMID , 0) to remove a shared segment. The man 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 and Process2), Process1 could create the shared memory, attach, detach, destroy the shared memory, and ultimately terminate. Then the memory will still exist until Process2 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.