3

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 ?

nav_jan
  • 2,473
  • 4
  • 24
  • 42

2 Answers2

4

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."

Piotr Wadas
  • 1,838
  • 1
  • 10
  • 13
  • @Piotr one more question : If a process opens a semaphore and exits without calling `sem_close` and `sem_unlink`. Is there a way to delete it without system shut down. We cannot use `ipcrm -s` here as these are posix semaphore. – nav_jan Jun 12 '13 at 12:11
  • The answer is on the same manpage. Actually at least three valid answers :) – Piotr Wadas Jun 12 '13 at 12:15
1

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.

Pradheep
  • 3,553
  • 1
  • 27
  • 35