Cleaning up POSIX shared objects upon termination / death of a process

Is there a way to clean up shared POSIX synchronization objects, especially if the process crashes? Locked unlocks of POSIX semaphores are the most desirable thing, but automatically “collected” queues / shared memory area would also be good. Another thing to watch out for is that we cannot use signal handlers at all because of SIGKILL, which cannot be caught.

I see only one alternative: some external daemon that accepts subscriptions and "keep-alive" requests that work as a watchdog timer, so without any notifications about any object, it could close / unlock the object in accordance with the registered policy.

Does anyone have a better alternative / suggestion? I have never seriously worked with POSIX shared objects (sockets were enough for all my needs and much more useful in my opinion), and I did not find a suitable article. I would love to use sockets here, but could not for historical reasons.

+4
source share
3 answers

Instead of using semaphores, you can use file locking to jointly control your processes. The big advantage of file locks is that they are freed if the process terminates. You can map each semaphore to a byte lock in the shared file and know that the locks will be released upon exit; in most versions of unix, the bytes you block should not even exist. There is a code for this in Mark Rochkind’s book "Advanced Unix Programming" of the 1st edition, I don’t know if it was in the last 2nd release.

+3
source

The usual way is to work with signal handlers . Just catch the signals and call the cleaning function.

But your guard demon has some advantages. This will undoubtedly make the system more understandable and manageable. To simplify administration, your application should start the daemon when it is not running, and the daemon will be able to clear any residue from the last failure.

+2
source

I know this question is old, but another excellent solution is the reliable POSIX mutexes. They automatically unlock and enter the state of an "inconsistent flag" when the owner dies, and the next thread to try to lock the mutex receives an EOWNERDEAD error, but it becomes the new owner of the mutex. It can then clear all mutex-protected states (which may be in a very bad inconsistent state due to the asynchronous completion of the previous owner!) And mark the mutex as sequentially again before unlocking it.

See the documentation for robust mutexes here:

http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_lock.html

+2
source

All Articles