File locking using fcntl.flock()

Donn Cave donn at u.washington.edu
Tue Apr 16 13:38:54 EDT 2002


Quoth Richard Jones <rjones at ekit-inc.com>:
| I can't get any locking to work on Solaris 5.7 using python 2.1.3. On Linux 
| 2.4.9, I get an exception when I try to re-lock something that's locked. On 
| Solaris, I don't get the exception (and without LOCK_NB, I don't block 
| either). I've also tried the lockf and posixfile.lock methods to no avail.
|
|>>> import fcntl
|>>> f=open('foo', 'w')
|>>> fcntl.flock(f.fileno(), fcntl.LOCK_EX)
|>>> f2=open('foo', 'w')
|>>> fcntl.flock(f2.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)

I don't have Solaris, but I bet it doesn't have flock.  The real
flock() is more of a Berkeley UNIX thing.  Today you'll get it
on (Net/Free/Open)BSD & Darwin, Linux, Digital UNIX and probably
others.

The other locking function is the F_SETLK etc. option to fcntl,
which is specified in POSIX 1003.1 and supported by all modern
UNIX platforms.  And it's supported over NFS, where flock(2)
is not.  On the other hand, its semantics are bizarre.  Probably
the worst part is that a lock is removed when the process closes
_any_ file descriptor open on that file.  I have personally seen
this cause some havoc even when the programmer (not me) knew all
about the problem.  Another quirk is that, as you can see, it
doesn't support interlocking within a process, while flock() does.
This fcntl option is also invoked as lockf().

I think HP/UX 10.20 just doesn't have flock, period.  AIX makes
the worst of it, as usual, by providing an "flock" that just
calls fcntl.  I don't know which way Solaris goes, but it really
doesn't matter - because Python flock likewise calls fcntl if
true flock isn't supported.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list