I am trying to use POSIX named semaphore for cross-process synchronization. I noticed that after the process died or exit, the semaphore is still open by the system.
Is there anyway to make it closed/released after the process (which open it) die or exit?
An earlier discussion is here: How do I recover a semaphore when the process that decremented it to zero crashes?. They discussed several possible solutions there.
In short:
Other links that might help:
You seem to be having a conceptual problem with inter-process communication. An IPC mechanism's lifetime cannot be tied directly to the life cycle of any one process because then it could disappear out from under other processes accessing it. It is intentional that named semaphores persist until explicitly removed.
The Linux sem_overview(7)
manual page, though not an authoritative specification, gives a run-down of semaphore life cycle management:
The sem_open(3) function creates a new named semaphore or opens an existing named semaphore. After the semaphore has been opened, it can be operated on using sem_post(3) and sem_wait(3). When a process has finished using the semaphore, it can use sem_close(3) to close the semaphore. When all processes have finished using the semaphore, it can be removed from the system using sem_unlink(3).
As the documentation for sem_unlink()
makes clear, you can unlink a semaphore while processes still have it open. No processes can thereafter sem_open()
that semaphore, and ultimately it will be cleaned up when the number of processes that have it open falls to zero. This is intentionally analogous to regular files.
If indeed there is one process that should be responsible for cleaning up a given named semaphore, then you should be sure that it sem_unlink()
s it. Two reasonably good alternatives are to unlink it as soon as you are satisfied that all other processes that need it have opened it, or to register an exit handler that handles the unlinking. If viable, the former is probably better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With