From the man page of shm_unlink
:
The operation of shm_unlink() is analogous to unlink(2): it removes a
memory object name, and, once all processes have unmapped the object,
de-allocates and destroys the contents of the associated memory
region. After a successful shm_unlink(), attempts to shm_open()
an object with the same name fail (unless O_CREAT was specified,
in which case a new, distinct object is created).
The working of this is specified by the sentence
it removes a memory object name, and, once all processes have unmapped the object, de-allocates and destroys the contents of the associated region
So, does that mean when shm_unlink
is called, unmapping will be done on all the processes automatically and then the destruction will take place, or will it still exist and as soon as all the processes using this space have unmapped this space (as per their convenience in the future), it will be destroyed?
The above description is the man pages is a bit under descriptive and this can be interpreted in the above two ways, hence my doubt.
The culprit is here:
[...] once all processes have unmapped the object, de-allocates and destroys the contents of the associated region.
The keyword is unmapped.
Calling shm_unlink()
will only affect the calling process, not others that already have the region mapped. If other processes already have that region of shared memory mapped into their address space, it will still be valid for them. This works the same way as it does with files. If a process opens (maps) a file, and a second process deletes it through unlink
, the first process will still be able to read the file contents from the mapped memory pages.
If the region is shared with multiple processes, the kernel will wait for all of them to unmap the region and close the file descriptor obtained from shm_open()
, and only then it will de-allocate and destroy the contents of the associated memory region. Even if shm_unlink()
is called, the kernel must wait before every single process closes their descriptor or terminates (at which point descriptors are automatically closed by the kernel itself).