Help: using msvcrt for file locking

David Bolen db3l at fitlinxx.com
Mon Aug 27 21:47:13 EDT 2001


Sheila King <sheila at spamcop.net> writes:

> Thanks. I'm looking at that, and it looks like it might be a very good
> approach.

Ah, well just to kick start things - here's a lock function that one
of my backup scripts uses to lock the database backup files in a
directory before beginning retrieval of the backup to a central
location (to avoid the remote host starting a new backup).  Nothing
fancy, just some periodic attempts.  Since CreateFile doesn't have the
concept of a timeout to obtain the lock, you have to handle your own
retries.  Under heavy load, this does mean in theory it's possible for
one process to starve and never get the lock, depending on the retry
time.

When the process is done, just "win32file.CloseHandle(lock_file)" on
the handle returned from this function.

Since it's an open file lock, if the process owning it happens to die,
the file will still be around, but the next process to try will be
able to open it without problems.  To be nice, my backup task does
explicitly try to remove the lock file when done (inside a try/except
clause in case someone else immediately grabs the lock).

	  - - - - - - - - - - - - - - - - - - - - - - - - -
def LockDB(LockName):
    lock_file = None

    # Attempt to open lock file to ensure access.  We keep trying
    # to obtain lock for up to 60 seconds, trying every 10
    lock_start   = time.time()
    lock_current = lock_start
    while (1):
        try:
            lock_file = win32file.CreateFile(LockName,
                                             win32file.GENERIC_WRITE,
                                             0,   # Exclusive access
                                             None,
                                             win32file.OPEN_ALWAYS,
                                             0,0)
        except:
            if (lock_current == lock_start):
                traceback.print_exc(0)
                print "Waiting for database backup lock file \"%s\"" % \
                      LockName

            if ((lock_current - lock_start) < 60):
                time.sleep(10)
                lock_current = time.time()
            else:
                print "Unable to obtain access to database backup lock file"
                break

        else:
            break

    return lock_file
	  - - - - - - - - - - - - - - - - - - - - - - - - -

--
-- 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