[fcntl]how to lock a file

marcello marcs2006 at gmail.com
Thu Apr 6 11:49:04 EDT 2006


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...)

Untill now i have tried to do smthing like :
import fcntl
f=open("prova.txt", 'w')
fcntl.flock(f.fileno(),fcntl.LOCK_EX)
f.write("aaa")

#meanwhile i open prova.txt with an editor in another window
#and write in  "bbb" (without getting any error/warning)and then follow 
#in the python shell with

f.close()

But then opening the file i can see "bbb" instead of "aaa"
I'm wandering, am i completely lost(misled?)Am i waiting for fcntl to do 
what it doesn't?

I have tried too with:

f1=os.open('prova.txt',os.O_EXCL|os.O_APPEND)
os.write(f1,"qlcosa")
that should solve the problem of the order of the step, but i not even 
can write from the python shell with that.

python 2.2
linux
kernel 2.4
glibc-2.3.2-95.6

Thanks in advance for any help.
sorry for my bad english
Grazie
Marcello



More information about the Python-list mailing list