[Tutor] Locking a file in linux with Python

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Feb 22 23:01:11 CET 2006



On Wed, 22 Feb 2006, Pat Martin wrote:

> I had actually looked at that site, but when I do the commands
>
> 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...


Hi Pat,

Oh!  Ok, what's happening is that the code places an "advisory" lock.
Any other program that tries to get a lock will wait as expected.  But a
noncooperating program that doesn't look at locks won't care.

It's possible that 'vi' is not cooperating: it may not be doing an flock()
call.  There is a line item in the vim TODO documentation about this:

    """
    8 Add file locking.  Lock a file when starting to edit it with flock()
    or fcntl().  This patch has advisory file locking while
    reading/writing the file: ~/vim/patches/kahn_file_locking.
    """

    (http://www.vim.org/htmldoc/todo.html)


For more information on this situation, see:

    http://en.wikipedia.org/wiki/File_locking


You might be able to put wrappers to force a common access point to the
file you're trying to lock; an example of this approach is in the 'visudo'
program that tries to provide exclusive access to /etc/sudoers.

I have to admit that I don't know much more about this or how people work
around exclusive access to files; does anyone else on the Tutor list have
suggestions?


Good luck to you!



More information about the Tutor mailing list