473,667 Members | 2,664 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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,f cntl.LOCK_EX)

but this does not work:

import fcntl

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

lock()

Nov 4 '05 #1
3 6582
The file you open() may be closed as soon as it is no longer possible to refer to it.

So in the first case, because the top-level variable 'f' continues to refer to the opened
file, the file may not be closed.

In the second case, no variable refers to the opened file after lock() returns, so Python is
free to close the file at any time. In fact, Python happens to close the function exactly
when lock() returs.

If you want an open file descriptor that is not automatically closed, use os.open(). Or,
store the file descriptor somewhere so you can later close() or unlock it at an
appropriate time.

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFDa7mIJd0 1MZaTXX0RAqZAAJ 4tMGFkwBW7UqxzE FsDAx4UATWMrACf Q/Kt
6l+08cC3mkR+afg NY0QbI/c=
=NRVX
-----END PGP SIGNATURE-----

Nov 4 '05 #2
In article <11************ **********@z14g 2000cwz.googleg roups.com>,
thakadu <th*****@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,f cntl.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,f cntl.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 (je*@jes-2.demon.nl)

Nov 4 '05 #3
Thank you both for your replies. You are both quite correct and upon
testing I get the desired results. I was mistakenly expecting the
execution of the function to block at the fcntl.flock(f,f cntl.LOCK_EX)
line.
But I am slowly getting my head around it.

Thanks

Nov 4 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
7887
by: writeson | last post by:
Hi all, I've got a PHP program that I've added flock() to in order to protect multiple scripts trying to write to the same file. After I added the flock() to the code the performance of the code went way down. Can anyone tell me if calling flock() on a file handle is particularly slow? Thanks, Doug
6
3816
by: Pierre Rouleau | last post by:
Hi all! I am using Python 2.3.1 on Win32 (NT, 2000). Whenever a file imports the standard tempfile module, Python 2.3.1 issues the following warning: C:\Python23\lib\fcntl.py:7: DeprecationWarning: the FCNTL module is Deprecated; please use fcntl DeprecationWarning).
0
1550
by: Ryan Grow | last post by:
Hi, I'm trying to use fcntl to set an existing file descriptor to be nonblocking. This contrived example exhibits the behavior of python that is preventing me from doing this: import os, fcntl, FCNTL file = open("/tmp/testfd.txt", 'w')
3
2273
by: Rob McCrea | last post by:
Hi all, On windows98SE, running Python 2.3.4 (#53, May 25 2004, 21:17:02) on win32, the built-in help() function gives me a deprecation warning when used on my docstrings. just help() start the interactive help without error. Heres some minimalistic code to demonstrate this warning: """start testhelp.py"""
0
1007
by: John Lenton | last post by:
In the fnctl docs for both python 2.3 and 2.4 there is a note at the bottom that says The os.open() function supports locking flags and is available on a wider variety of platforms than the lockf() and flock() functions, providing a more platform-independent file locking facility. however, in neither of those versions does os.open support any kind of mysterious "locking flags", nor is there any reference in os to any
5
12287
by: marcello | last post by:
Hello I need to do this: 1 opening a file for writing/appending 2 to lock the file as for writing (i mean: the program that lock can keep writing, all others programs can't ) 3 wtite and close/unlock Even better would be changing the order of steps 1 and 2 (that is,first locking than writing, but it seems to me that in order to block i need the id of the file...)
0
1792
by: Mitko Haralanov | last post by:
I am trying to use the advisory locking with fcntl over NFS (thus, me choosing fcntl instead of flock and friends). I have the following code: lockdata = struct.pack ("hhllhh", fcntl.F_RDLCK, 0, 0, 0, 0, 0) print self.fd, type (self.fd), len (lockdata), type (lockdata) ret = fcntl.fcntl (self.fd, fcntl.F_GETLK, lockdata) when this code executes, I always get the following:
9
5389
by: mhearne808[insert-at-sign-here]gmail[insert-dot-he | last post by:
I'm having a number of problems with the fcntl module. First off, my system info: Mac OS X Darwin igskcicglthearn.cr.usgs.gov 8.10.1 Darwin Kernel Version 8.10.1: Wed May 23 16:33:00 PDT 2007; root:xnu-792.22.5~1/RELEASE_I386 i386 i386 Python 2.5.1 (built from source) OK, the weirdness:
2
3643
by: xucs007 | last post by:
I ran following 2 programs (lock1, lock2) at almost same time, to write either "123456", or "222" to file "aaa" at the same time. But I often just got "222456" in "aaa" . Is this a bug of python fcntl module ? See 2 programs I ran: #!/usr/bin/env python import fcntl, time
0
8888
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8790
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8565
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6206
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4202
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4372
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2779
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2017
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1779
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.