Locking a file under Windows

G

Guy Lateur

Hi all,

I'm working on an application that will be used by several users at the same
time. The user should be able to both read and write to some data file
stored on our file server. My question is: how can I prevent that one user
writes to the file while another user is reading it?

I've seen some info on this in the fcntl module, but this module is not
available under Windows, so I need something else. Here is what I've come up
with so far:

def WriteToFile(filename):
for i in range(max_nr_tries):
try:
fd = os.open(filename, os.O_EXCL | os.O_WRONLY)
except OSError, (error, message):
if error == errno.ENOENT:
# create first
try:
fd = os.open(filename, os.O_CREAT | os.O_EXCL |
os.O_WRONLY)
break
except:
print "Oops!"
else:
# try again later
time.sleep(1)
continue
time.sleep(20)
# + write & close file

I thought that, when this function gets to the last sleep(), I'd have an
exclusive lock on the file. However, it seems I can still open the same file
for reading/writing in another process (even os.O_EXCL).

Is this normal? What am I missing? How can I open a file exclusively (for
writing)?

Thanks,
g
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top