In article < XXXX@XXXXX.COM >,
% > In article < XXXX@XXXXX.COM >,
% > % In one of my projects, I need to create a mutex in shared memory using
% > % memory-mapped I/O in order to achieve inter-process synchronization
% > % for updating a data file;
% > [...]
% > % The problem is, if I killed a process in the middle, it would leave a
% > % stale mutex file in hard disk (without unlocking it?).
% > That's one problem. Another is that, if you kill a process in the middle,
% > the data file will be corrupt.
% > If you want to handle this situation, you need to have a clean-up
% > strategy. This will include detecting that the process modifying
% > the data file is gone, detecting wither the file is in an inconsistent
% > state, rolling back the incomplete changes, destroying the old mutex
% > and creating a new one.
% You may also use NO_OWNER mutexes, so that you can unlock the mutex
% if you see some inconsistancy and found that the mutex is in locked state.
OK, rather than using the standard mutexes, you could use some other
kind, say process-shared semaphores. In that case, rather than detecting
that the process modifying the data file is gone, detecting whether the
file is in an inconsistent state, rolling back the incomplete changes,
destroying the old mutex and creating the new one, you can detect that
the process modifying the data file is gone, determine whether the file
is in an inconsistent state, roll back the incomplete changes, and go up
on the the semaphore.
If this seems simpler to you or it makes you happier in some way, go for
it. My experience is that semaphores tend to be slower than mutexes on
systems which allow both to be shared between processes, but do your
locking however you like. It doesn't change the core part of the
problem, which has nothing to do with restoring the mutex. Restoring the
mutex is trivial.
Patrick TJ McPhee
East York Canada