473,545 Members | 2,010 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to lock files (the easiest/best way)?

Is there something better than using fnctl? It seems a bit intimidating
with a quick look.
Jul 15 '06 #1
12 5422
On Sat, 15 Jul 2006 23:28:21 +0200, Sybren Stuvel wrote:
Elmo Mäntynen enlightened us with:
>Is there something better than using fnctl? It seems a bit
intimidating with a quick look.

Locking files is a complex business. What do you want to lock? Why?
Lock it with respect to what? It's easier to lock a file for local
use, compared to when the file also has to be locked from, say, use
via the network.

Sybren
Only locally. I want to be able to read/write to a single file from
multiple possibly parallel processes. Would 'touch lock' (or something
like that) work reliably (this just occured to me)?
Jul 15 '06 #2
On Sat, 15 Jul 2006 23:52:10 +0200, Sybren Stuvel wrote:
Elmo Mäntynen enlightened us with:
>Only locally. I want to be able to read/write to a single file from
multiple possibly parallel processes. Would 'touch lock' (or
something like that) work reliably (this just occured to me)?

I use a lock directory for that, os.mkdir('/var/lock/somedir').
If you use a file, you need two steps:
1) Check whether the lock-file exists
2) Create the lock-file

This is not atomic. With a directory, creating it will fail if it
already exists. This means you can atomically check for the lock, and
if it doesn't exist already, you've immediately created it too.

Sybren
Thanks. Is that what atomic basically means?
Jul 15 '06 #3
On 2006-07-15 18:52:10, Sybren Stuvel wrote:
Elmo Mäntynen enlightened us with:
>Only locally. I want to be able to read/write to a single file from
multiple possibly parallel processes. Would 'touch lock' (or
something like that) work reliably (this just occured to me)?

I use a lock directory for that, os.mkdir('/var/lock/somedir').
If you use a file, you need two steps:
1) Check whether the lock-file exists
2) Create the lock-file
cvsnt for example used to use lock files. Now it uses a lock server: a
server app that just sits there and allows different processes to acquire,
check for and release locks on files. More implementation work, probably,
but more efficient.

Gerhard

Jul 15 '06 #4
Sybren Stuvel <sy*******@YOUR thirdtower.com. imaginationwrit es:
I use a lock directory for that, os.mkdir('/var/lock/somedir').
If you use a file, you need two steps:
1) Check whether the lock-file exists
2) Create the lock-file
This is not atomic. With a directory, creating it will fail if it
already exists. This means you can atomically check for the lock, and
if it doesn't exist already, you've immediately created it too.
The classic way in Unix was to make a link:

1) link('some_othe r_file', 'lockfile')

This was atomic and would fail if lockfile already existed.

I'm not sure whether it can still be reliable, in current environments
that can involve remote file systems etc. But I'm not sure if the
mkdir approach works either.

Maybe you want to use something like shm or posh?
Jul 16 '06 #5
Elmo Mäntynen wrote:
Is there something better than using fnctl? It seems a bit intimidating
with a quick look.
try the portlocker wrapper from the active state cookbook. I have a
version which has been slightly updated for more modern pythons. I
really need to make my darcs repository visible so you could get it.

Alternatively, you can try the makedir trick. Creating directories are
atomic operations if it exists, you will get error message. If it
doesn't, you will get a directory and thereby capture the lock. You
delete the directory when you release the lock.

crude but effective. I used it in building a file based queue system.
You know, I really should learn how to build eggs because I have a whole
bunch of little pieces of software that would probably be useful to others.

---eric

Jul 16 '06 #6
In article <ma************ *************** ************@py thon.org>,
Eric S. Johansson <es*@harvee.org wrote:
>Elmo Mäntynen wrote:
>Is there something better than using fnctl? It seems a bit intimidating
with a quick look.

try the portlocker wrapper from the active state cookbook. I have a
version which has been slightly updated for more modern pythons. I
really need to make my darcs repository visible so you could get it.

Alternativel y, you can try the makedir trick. Creating directories are
atomic operations if it exists, you will get error message. If it
doesn't, you will get a directory and thereby capture the lock. You
delete the directory when you release the lock.

crude but effective. I used it in building a file based queue system.
You know, I really should learn how to build eggs because I have a whole
bunch of little pieces of software that would probably be useful to others.
Here's a more complete file locking scheme which uses a lockfile with
the O_CREAT and O_EXCL flags to make the creation atomic. If it gets
the lock, it writes its PID in readable form in the file. It also does
two other things:

If you know that no process should lock the file for more than a fixed
period of time, it will retry once/second as long as the lock file is
not older than that fixed period of time. If it is older, it will
report the problem, including the PID of the locking process and exit.

This caters for a process which has set the lock file and then
terminates without removing it (which can happen do to an application
or server crash).

------------------------------------------

import os
import errno
import sys
import time
import stat

# the maximum reasonable time for aprocesstobe
max_wait = 10

lockfile = "/tmp/mylock"

while True:
try:
fd = os.open(lockfil e, os.O_EXCL | os.O_RDWR | os.O_CREAT)
# we created the lockfile, so we're the owner
break
except OSError, e:
if e.errno != errno.EEXIST:
# should not occur
raise

try:
# the lock file exists, try to stat it to get its age
# and read it's contents to report the owner PID
f = open(lockfile, "r")
s = os.stat(lockfil e)
except OSError, e:
if e.errno != errno.EEXIST:
sys.exit("%s exists but stat() failed: %s" %
(lockfile, e.strerror))
# we didn't create the lockfile, so it did exist, but it's
# gone now. Just try again
continue

# we didn't create the lockfile and it's still there, check
# its age
now = int(time.time() )
if now - s[stat.ST_MTIME] max_wait:
pid = f.readline()
sys.exit("%s has been locked for more than " \
"%d seconds (PID %s)" % (lockfile, max_wait,
pid))

# it's not been locked too long, wait a while and retry
f.close()
time.sleep(1)

# if we get here. we have the lockfile. Convert the os.open file
# descriptor into a Python file object and record our PID in it

f = os.fdopen(fd, "w")
f.write("%d\n" % os.getpid())
f.close()


--
Jim Segrave (je*@jes-2.demon.nl)

Jul 16 '06 #7
In article <12************ *@corp.supernew s.com>,
Jim Segrave <je*@jes-2.demon.nlwrote :
except OSError, e:
if e.errno != errno.EEXIST:
this should read:
if e.errno != errno.ENOENT:

(it was left with EEXIST from testing this code by forcing an error,
as the code for this failure requires a very tight race condition to test)
sys.exit("%s exists but stat() failed: %s" %
(lockfile, e.strerror))
# we didn't create the lockfile, so it did exist, but it's

--
Jim Segrave (je*@jes-2.demon.nl)

Jul 16 '06 #8
In article <pa************ *************** *@jippii.fi>,
Elmo Mäntynen <el****@jippii. fiwrote:
On Sat, 15 Jul 2006 23:52:10 +0200, Sybren Stuvel wrote:
Elmo Mäntynen enlightened us with:
Only locally. I want to be able to read/write to a single file from
multiple possibly parallel processes. Would 'touch lock' (or
something like that) work reliably (this just occured to me)?
I use a lock directory for that, os.mkdir('/var/lock/somedir').
If you use a file, you need two steps:
1) Check whether the lock-file exists
2) Create the lock-file

This is not atomic. With a directory, creating it will fail if it
already exists. This means you can atomically check for the lock, and
if it doesn't exist already, you've immediately created it too.

Sybren

Thanks. Is that what atomic basically means?
Yes, and also "race condition". That's why Jim Segrave's
example code uses O_EXCL with open(2).

Donn Cave, do**@u.washingt on.edu
Jul 17 '06 #9

Sybren Stuvel wrote:
Elmo Mäntynen enlightened us with:
Only locally. I want to be able to read/write to a single file from
multiple possibly parallel processes. Would 'touch lock' (or
something like that) work reliably (this just occured to me)?

I use a lock directory for that, os.mkdir('/var/lock/somedir').
If you use a file, you need two steps:
1) Check whether the lock-file exists
2) Create the lock-file

This is not atomic. With a directory, creating it will fail if it
already exists. This means you can atomically check for the lock, and
if it doesn't exist already, you've immediately created it too.
`Pathutils <http://www.voidspace.o rg.uk/python/pathutils.html> `_ has a
simple interface to a system like this.

Apparently not all platforms guarantee that attempts to create a
directory will fail if the directory already exists - so pathutils does
*slightly* more, but it's the same idea.

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

>
Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
Jul 17 '06 #10

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

Similar topics

3
1528
by: Mr. B | last post by:
In my application which allows a user to open specific AutoCAD script files (SCR extension), I want to intoduce a listing of the 10 most recently opened files. I know of at least two ways that I could do this: 1) Have a text file that contains the information 2) Write the info to the Registry The first is my easiest as I am familiar with...
3
2273
by: Steven Burn | last post by:
The application; Service on my webserver that allows a user to upload their HOSTS file for functions to verify the contents are still valid. Uses; 1. XMLHTTP (MSXML2) 2. FileSystemObject 3. CrazyBeavers Upload control (couldn't get the Dundas one to work)
7
703
by: Sunny | last post by:
Hi, I can not understend completely the lock statement. Actally what is locked: 1. the part of the code between {...} or 2. the object in lock() In the docs is written: for 1: The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a
18
2276
by: UJ | last post by:
Folks, We provide custom content for our customers. Currently we put the files on our server and people have a program we provide that will download the files. These files are usually SWF, HTML or JPG files. The problem as I see it - if you know the name of the file, you could download it off the server (currently we are using an HTTP/Get but...
9
2565
by: csharpula csharp | last post by:
Hello, I want to lock a boolian variable but it's not possible in c#,is there a way to convert it to something that is possible to lock? Thank you! *** Sent via Developersdex http://www.developersdex.com ***
4
1684
by: UJ | last post by:
What's the easiest/best way to open a single file from multiple applications but so only one can read it at a time? I tried a mutex but had problems. I noticed there is something called a ReaderWriter class but it says it's best for reads. I'll never be reading the file..... TIA - Jeff.
20
1928
by: Kurt | last post by:
Below is a class that can accessed from multiple threads and I want the class to be thread safe. I have a private timer member whose interval can be changed by different threads. Which is the correct way to define the property below. Thanks Kurt Class1 { private Timer _timer = new Timer(); // Example 1
8
1858
by: VJ | last post by:
I want to put a lock on my App's data directory (and all subdirectories below) when my application launches, so you can't delete through explorer or any other program. How is that possible. VJ
94
30223
by: Samuel R. Neff | last post by:
When is it appropriate to use "volatile" keyword? The docs simply state: " The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock Statement (C# Reference) statement to serialize access. " But when is it better to use "volatile" instead of "lock" ?
0
7473
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7660
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. ...
0
7813
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...
0
7761
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5337
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...
0
4949
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
1888
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
1
1020
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
709
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...

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.