fcntl.flock() not working when called from a function

Jim Segrave jes at nl.demon.net
Fri Nov 4 14:45:29 EST 2005


In article <1131132819.081353.213180 at z14g2000cwz.googlegroups.com>,
thakadu <thakadu at gmail.com> wrote:
>The following code works as expected when run in the main body of a
>python script (ver 2.3.5) on OpenBSD v3.8. but when it is in the body
>of a function definition it does not work. It does not raise any errors
>but it simply does not block as expected. I have repeated this in both
>a cgi envirnoment and a non-cgi environment. I also have repeated it
>under OpenBSD 3.6 Python Version 2.3.4. To test this you need to run
>the code from two shells or if testing the cgi version from two
>browsers.
>The first call to flock() should pass without blocking while the second
>call should block.
>I have tried varying the file open mode by using 'r', 'r+', 'w', 'rw',
>'w+', and always I get the same results.
>Does anyone have an idea why this would work in the main body of the
>script but not in a function?
>
>This code works if in the main body of a script:
>
>import fcntl
>f=open('/tmp/lockfile')
>fcntl.flock(f,fcntl.LOCK_EX)
>
>but this does not work:
>
>import fcntl
>
>def lock():
>    f=open('/tmp/lockfile')
>    fcntl.flock(f,fcntl.LOCK_EX)
>
>lock()

Doesn't f go out of scope when you exit lock()? Python closes the
file, as it's no longer referenced and Unix removes locks on calls to
close().
To make this work, you'd have to keep a reference to f:

import fcntl

def lock():
    f=open('/tmp/lockfile')
    fcntl.flock(f,fcntl.LOCK_EX)
    return f
saveme = lock()

print "OK"
while True:
    pass

Under FreeBSD, the first copy prints OK and waits for a SIGINT, the
second copy prints nothing. Killing the first copy prints OK on the
second one



-- 
Jim Segrave           (jes at jes-2.demon.nl)




More information about the Python-list mailing list