When to call sem_unlink()?

user2124642 picture user2124642 · Mar 1, 2013 · Viewed 12.1k times · Source

I'm a little confused by the Linux API sem_unlink(), mainly when or why to call it. I've used semaphores in Windows for many years. In Windows once you close the last handle of a named semaphore the system removes the underlying kernel object. But it appears in Linux you, the developer, needs to remove the kernel object by calling sem_unlink(). If you don't the kernel object persists in the /dev/shm folder.

The problem I'm running into, if process A calls sem_unlink() while process B has the semaphore locked, it immediately destroys the semaphore and now process B is no longer "protected" by the semaphore when/if process C comes along. What's more, the man page is confusing at best:

"The semaphore name is removed immediately. The semaphore is destroyed once all other processes that have the semaphore open close it."

How can it destroy the object immediately if it has to wait for other processes to close the semaphore?

Clearly I don't understand the proper use of semaphore objects on Linux. Thanks for any help. Below is some sample code I'm using to test this.

int main(void)
{
    sem_t *pSemaphore = sem_open("/MyName", O_CREAT, S_IRUSR | S_IWUSR, 1);
    if(pSemaphore != SEM_FAILED)
    {
        if(sem_wait(pSemaphore) == 0)
        {
            // Perform "protected" operations here

            sem_post(pSemaphore);
        }

        sem_close(pSemaphore);
        sem_unlink("/MyName");
    }

    return 0;
}

Answer

rg_sw picture rg_sw · Feb 23, 2014

Response to your questions:

  1. In comparison to the semaphore behavior for windows you describe, POSIX semaphores are Kernel persistent. Meaning that the semaphore retains it's value even if no process has the semaphore opened. (the semaphore's reference count would be 0)

  2. If process A calls sem_unlink() while process B has the semaphore locked. This means the semaphore's reference count is not 0 and will not be destructed.

Basic operation of sem_close vs sem_unlink, I think will help overall understanding:

sem_close: close's a semaphore, this also done when a process exits. the semaphore still remains in the system.

sem_unlink: will be removed from the system only when the reference count reaches 0 (that is after all processes that have it open, call sem_close or are exited).

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