fcntl example

Andy Bensky (ab@infoseek.com)
Mon, 2 May 1994 14:49:33 -0700

I had a need for a way to do some simple file locking which was not
provided with the builtin file object (why not??). I found some old
postings to this list talking about fcntl, but there were no examples.
In case anyone else is in the same boat here is the lockfile.py module
that I wrote to handle simple locking of full files. This does not
implement record locking but it is pretty easy to see how to extend it
to do that if you need to.

#
# lockfile.py
# functions to lock a file specified by an open file object
#
# Copyright (c) 1994 InfoSeek Corp. All Rights Reserved
# Permission granted for unlimited non-commercial use provided that
# this notice is included in all distributions.
#
# all functions act on an open file object.
# all functions return 1 if successful, otherwise they return 0 and
# set errno to the appropriate value.
#

import struct # used to pack the flock structure
import fcntl # needed for file locking and other file operations
import fcntlh # values used by fcntl. created using h2py from
# /usr/include/sys/fcntl.h

def writelock( f ):
fd = f.fileno()
flock = struct.pack('2h8l', fcntlh.F_WRLCK, 0, 0, 0, 0, 0, 0, 0, 0, 0)
if fcntl.fcntl(fd, fcntlh.F_SETLKW, flock) != -1:
return 1
else:
return 0

def readlock( f ):
fd = f.fileno()
flock = struct.pack('2h8l', fcntlh.F_RDLCK, 0, 0, 0, 0, 0, 0, 0, 0, 0)
if fcntl.fcntl(fd, fcntlh.F_SETLKW, flock) != -1:
return 1
else:
return 0

def unlock( f ):
fd = f.fileno()
flock = struct.pack('2h8l', fcntlh.F_UNLCK, 0, 0, 0, 0, 0, 0, 0, 0, 0)
if fcntl.fcntl(fd, fcntlh.F_SETLKW, flock) != -1:
return 1
else:
return 0