locking files

Donn Cave donn at u.washington.edu
Wed Feb 21 19:40:57 CET 2001


Quoth Joseph Holland King <insanc at cc.gatech.edu>:
| Joseph Holland King <insanc at cc.gatech.edu> wrote:
| : is there anyway to lock a file so that two different programs cannot access
| : the file at the same time. ie, my python module is editting file foo, and
| : at the same time user x (or program x) tries to read from it. is there 
| : anyway that the python module can prevent x from accessing the file for
| : a given amount of time?
|
| to clarify: i am on a unix system, i have tried to use flock however when i
| locked the file i was still able to read, write and copy the file, none of 
| which i want to happen while the file is locked. while using the flock 
| method i was using LOCK_EX. also the third party program is not going to be
| controlled, written, or have anything to do with mine. am i just not using
| flock properly or is there something else that might do the job? thank you.

Basically, that's how file locking works.  It's advisory, for the benefit
of software components that are designed to work together.

But there is a variation that you can find supported on some filesystems,
where in combination with an obscure permission mode on the file the lock
becomes mandatory and effective against any and all I/O.  The permission
trick is setgid & not group execute, i.e., (oldperm | 02000) & ~010.  It
works for me on Digital UNIX local (AdvFS) filesystem.  I didn't try on
NFS, but from the documentation I doubt that it will work there.  It does
not work on NetBSD 1.5 local filesystem.  Where it does work, you must
use fcntl() or lockf() to obtain the lock, not a genuine flock().

While I'm here, let me add a little note about flock(), for the benefit
of those whose UNIX platforms don't have the deluxe man pages that you
get on NetBSD for example.  There are two kinds of locks, one obtained
by Berkeley flock() and the other by POSIX 1003.1 fcntl().  The lockf()
function is a different, X/Open interface that interoperates with fcntl().
Many modern platforms do not support a genuine flock().  Some of them
provide an flock() function that is actually implemented with fcntl(),
which means that the semantics of the lock are per fcntl() and not
flock().  Python follows this trend and does the same thing if there's
no flock(2), so it's up to the programmer to find out what kind of lock
fcntl.flock() really gets, if the difference is important.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list