Help: using msvcrt for file locking

David Bolen db3l at fitlinxx.com
Thu Aug 30 06:56:00 CEST 2001


Sheila King <sheila at spamcop.net> writes:

> So, you're saying that the way you usually handle exclusive access to
> objects, is by creating/removing directories? 

If I need to have a reliable means (or at least about as reliable as
possible) for gross-level locking compatibly cross-platform and
especially if NFS is involved (see my other recent post), then yes,
creating/removing directories is something I've used successfully in
the past.  If my target domain is more limited, then the range of
possibilities expand.

> Yes, I discovered that while testing, today. Ignacio had suggested that
> I needed a __del__ function for my classes, and I found out today, that
> on Linux, if an object had the lock and was deleted but that process
> still kept running, I could not recover the lock. I've written a __del__
> function, now, that seems to work. It unlocks the file and does cleanup.

You're still somewhat at risk if your process is forcibly killed but
without permitting cleanup.  Or if for example, your lock is across
the network but the source system for the lock crashes.

One approach that can be used is that in addition to creating the
sentinel file, once you "have the lock" create a PID file that
contains the PID of the process that has the lock.

When attempting to get the lock, if it fails, read the PID file and
then see if there is a process with that id on the system.  If so,
assume the lock is valid and wait.  You might be wrong if the actual
process died but the id got reused, but it's the more conservative
choice.  (If you know that all processes using the lock are a
particular executable you can add cross-checks for that).

If not, log nasty warnings in your log files or consoles, then go
ahead and remove the lock and then try to re-acquire.  Depending on
the timing requirements for a blocked system in the presence of
crashes, you can have this cleanup performed by an independent task at
some regular interval.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list