Reputation: 2553
I am using named semaphore
in C
in Linux
to control the access of shared memory across multiple processes.
As of now I have not added any code to sem_close
and sem_unlink
the semaphore.
So my question is :
Do named semaphore automatically get destroyed when all processes using it are finished?
If yes then, is it ok not to call sem_close
and sem_unlink
at all ?
Upvotes: 3
Views: 1207
Reputation: 3819
From the man pages http://pubs.opengroup.org/onlinepubs/7908799/xsh/sem_close.html
The sem_close() function is used to indicate that the calling process is finished using the named semaphore indicated by sem. The effects of calling sem_close() for an unnamed semaphore (one created by sem_init()) are undefined. The sem_close() function deallocates (that is, make available for reuse by a subsequent sem_open() by this process) any system resources allocated by the system for use by this process for this semaphore. The effect of subsequent use of the semaphore indicated by sem by this process is undefined. If the semaphore has not been removed with a successful call to sem_unlink(), then sem_close() has no effect on the state of the semaphore.
If the sem_unlink() function has been successfully invoked for name after the most recent call to sem_open() with O_CREAT for this semaphore, then when all processes that have opened the semaphore close it, the semaphore is no longer be accessible.
So in essence when all the process that has opened the semaphore has successfully called sem_unlink and sem_close the semaphore is destroyed.
Upvotes: 1
Reputation: 1884
http://linux.die.net/man/7/sem_overview
"POSIX named semaphores have kernel persistence: if not removed by sem_unlink(3), a semaphore will exist until the system is shut down."
Upvotes: 4