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.
The shmdt() function detaches the shared memory segment specified by shmaddr from the calling job. The shmaddr is the value returned by the shmat() function.
On Windows: You can use Microsoft Process Explorer to check the shared memory handle of saposcol and then try to find if another process holds it. You should see that some disp+work has the handle. Kill this and then you should be able to stop saposcol and clean the memory.
The shmctl() function provides a variety of shared memory control operations on the shared memory segment identified by the argument, shmid. This command obtains status information for the shared memory segment specified by the shared memory identifier, shmid.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With