locking files

Christopher Lee clee at gnwy100.wuh.wustl.edu
Wed Feb 21 20:27:45 CET 2001

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.

flock() is an advisory lock, if you don't have cooperation from the other
processes, and if your system supports the SysV interface you can enable
mandatory locks.  "man lockf" or "man fcntl" and search for information on SysV
mandatory locking on your system.

Files are marked as candidates for mandatory file locking by setting the
file mode with SGID but without the "group execute" bits, (chmod g+s; chmod
g-x).  Enabling mandatory locking is system dependent, but you need to use
fnctl/lockf, flock is always advisory.

Under linux, I can do it like this:
[as root]
# enable file locking by remounting /home file system w/ mand flag
mount -o remount -o mand /home   

[as normal user]
> chmod g+s tmp; chmod g-x tmp
> python
>> import fcntl, FCNTL
>> fp = open("tmp", "rw")
>> fd = fp.fileno()
>> fcntl.lockf(fd, FCNTL.F_LOCK)  # secures the lock, prevents
                                  # reading/writing 

More information about the Python-list mailing list