How to lock files (the easiest/best way)?

pavlovevidence at gmail.com pavlovevidence at gmail.com
Mon Jul 17 17:52:54 EDT 2006


Elmo Mäntynen wrote:
> Is there something better than using fnctl? It seems a bit intimidating
> with a quick look.

Although fcntl is pretty opaque, it's quite easy to use if all you want
is a simple exclusive lock for all your data.  The thing to keep in
mind is, you don't have to lock every file you want exclusive access
to.  In fact, doing that provides no added security (since it's an
advisory lock and programs are free to ignore it).  For simple cases,
locking one file and only accessing your data if you have that lock
works, and is very simple.

What I usually do is touch an empty file (say, "lockfile") in my data
directory.  I don't access any files in that directory unless I have a
lock to the lockfile.  This is done simply with (untested):

import fcntl

f = open("/path/to/data/directory/lockfile","r")
try:
    fcntl.flock(f.fileno(),fcntl.LOCK_EX)
    ...access data freely here...
finally:
    f.close()

Closing the file should release the lock (unless you have a truly
horrible operating system).


Carl Banks




More information about the Python-list mailing list