问题
I have two programs interacting via a shared memory segment. When using the segment for read or write, they hold a lock.
Should either of them crash (get killed, typically - possibly with something untrappable) in a critical section, I would like them to release the lock so that the shmem isn't locked out completely.
Other questions point the way to the answer in Windows, Java, etc. but how do you do it in Unix (and specifically Linux)?
(I'm not attached to the pthreads mutex functions; SysV semaphores or anything else will do just fine.)
回答1:
I believe POSIX robust mutexes are what you're looking for:
http://www.opengroup.org/onlinepubs/9699919799/functions/pthread_mutexattr_getrobust.html
回答2:
I think this is by design. If one of the processes crashed, it's likely that the critical section being locked for got interrupted and the data stored in that shared memory segment is inconsistent, invalid, or unsafe. Accessing the memory and operating as though nothing happened from the other process could very well make it crash or worse, depending on what it does.
回答3:
System V semaphores support the SEM_UNDO
option to do exactly this. However, unlike robust mutexes this will not notify the next thread to acquire the lock. On the upside, they are more portable than robust mutexes.
来源:https://stackoverflow.com/questions/4149266/automatically-release-mutex-on-crashes-in-unix