sem_close vs sem_unlink when process terminates
Asked Answered
R

2

6

I have multiple processes communicating using a semaphore.

sem_open("\name",O_CREATE,S_IRWXU|S_IRWXG,10);

I have 2 questions w.r.t following:

  1. Now, when one process dies suddenly without calling sem_close or sem_unlink. What happens to the remaining processes ?

  2. If sem_close() is called, however sem_unlink() is not called for 1 process. All the other processes, call sem_close() and sem_unlink(). Does the semaphore still exists, after all the processes exit ?

Reena answered 2/3, 2012 at 16:44 Comment(1)
Related: When to call sem_unlink()?Kleist
W
9

In answer to your questions:

  1. when a process dies, voluntarily or unvoluntarily, the sem_close operation occurs automatically.
  2. No, the semaphore does not exist if all processes have exited which had the semaphore opened and at least one process has called sem_unlink.

To expand a bit: sem_unlink removes the named semaphore, and will destruct the semaphore once its reference count is 0. That is after all process that opened it have called sem_close or have exited.

References: Book - Unix Networking Programming-Interprocess Communication by W.Richard Stevens, vol 2, ch10

Worldling answered 22/2, 2014 at 23:26 Comment(0)
K
2

Late answer but nevertheless I find this information missing in the other answer:

  • sem_close is associated with the semaphore and its count
    • Semaphore's reference count would be decremented when called
    • Even when count drops to zero semaphore is still kept alive
    • Another process can sem_open with same name, restoring the count back to 1 (or greater with subsequent sem_opens)
  • sem_unlink is associated with a semaphore's name
    • Name is no longer taken when called; name is relinquished
    • Semaphores still open (i.e. without sem_close calls) are kept alive until ref. count drops to zero
    • When count drops to zero an unlinked semaphore is destroyed
    • If a process sem_opens with the same, now-unliked name, it'd get a completely new (different) semaphore

Though a semaphore associated with a name is sem_closed, the semaphore lives and name stays taken until it's sem_unlinked.

Kleist answered 11/4, 2022 at 13:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.