Detaching and Removing a Shared Memory Segment - shmdt() and shmctl()

System call shmdt() is used to detach a shared memory. After a shared memory is detached, it cannot be used. However, it is still there and can be re-attached back to a process's address space, perhaps at a different address. To remove a shared memory, use shmctl().

The only argument of the call to shmdt() is the shared memory address returned by shmat(). Thus, the following code detaches the shared memory from a program:

shmdt(shm_ptr);
where shm_ptr is the pointer to the shared memory. This pointer is returned by shmat() when the shared memory is attached. If the detach operation fails, the returned function value is non-zero.

To remove a shared memory segment, use the following code:

shmctl(shm_id, IPC_RMID, NULL);
where shm_id is the shared memory ID. IPC_RMID indicates this is a remove operation. Note that after the removal of a shared memory segment, if you want to use it again, you should use shmget() followed by shmat().