Search code examples
linuxposixsemaphoreglibc

How can I avoid resource leak when using a semaphore?


Linux sem_destroy() documentation says:

An unnamed semaphore should be destroyed with sem_destroy() before the memory in which it is located is deallocated. Failure to do this can result in resource leaks on some implementations.

But the best I can do is register sem_destroy() to atexit(), which won't be called on aborts or SIGKILL. I have a process responsible for creating and destroying a semaphore on shared memory (a mmaped file), how can I avoid a resource leak on abnormal termination conditions?

On Linux, if the mmaped file is deleted before sem_destroy() is called, is any kind of resource leaked? What resource?


Solution

  • The glibc implementation of sem_destroy does nothing, and this will not change. If you use glibc, you do not have to do anything for freeing up resources. Furthermore, the kernel would free such resources on process termination anyway.

    The glibc implementation of semaphores is based on futexes, which is why it does not need any additional resources besides the memory used to store the semaphore.