Reputation: 5767
I have code tht does
int shmId = shmget(key, shmBytes, IPC_CREAT | 0666 );
shmAddress = (char *) shmat(shmId, NULL, 0);
/* do some stuff */
/* detach */
shmdt(shmAddress);
My question is, do I ever need to de-allocate the segment I got with shmget? or does shmdt take care of this?
Thanks!
Upvotes: 1
Views: 1665
Reputation: 179717
If you're on Linux, you should consider using the POSIX shared memory system (shm_open
, shm_unlink
), which mostly uses the standard POSIX file API (mmap
, ftruncate
, etc.) to interact with shared memory regions. It's also noted as being more modern as the old SYSV interface that you're using.
Anyway, the way to destroy SYSV segments is to use shmctl(shmId, IPC_RMID, NULL)
before detaching the segment. From 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.
Upvotes: 3