[Tutor] Locking a file in linux with Python

Hugo González Monteverde hugonz-lists at h-lab.net
Thu Feb 23 18:46:30 CET 2006


Hi Pat,

> testfile = open('testlock', 'a+')
> fcntl.flock(mboxfile.fileno(), fcntl.LOCK_EX)
> 
> in the interpreter and then try to access the file in another terminal 
> (I leave the interpreter open) I can write to the file just fine with 
> vi. So I am not thinking it is working. Unless I am missing something...

Actually yes, all these locks are advisory, that is, you need to have 
all applications using the file use the protocol. In your case, vi does 
not honor the file lock.

Granted, this is not very useful for dealing with 3rd applications, as 
the operating system does not provide hard locks, and basically flock() 
is a mechanism for not having your own programs trample on files.

Try getting a lock in another terminal, for the same file, and check 
that it will not be granted and the other application will block until 
you release the lock in the first python interpreter...


Hope that clarifies things a bit,

Hugo


More information about the Tutor mailing list