简体   繁体   中英

python fcntl does not lock as expected (2)

I'd like to use LOCK_EX to prevent other processes to modify a file under modification.

Process A:

from fcntl import flock, LOCK_EX, LOCK_NB
from time import sleep
f=open("tmp.txt", "w")
flock(f.fileno(), LOCK_EX|LOCK_NB)
f.write("xxxx")
f.flush()
sleep(20)
f.close()

5 seconds after A starts, process B:

f=open("tmp.txt", "w")
f.close()

And "tmp.txt" is emptied by process B... No IOError is raised in process B. How can one prevent "tmp.txt" to be modified by 2 processes using exclusive access ?

Note: "innocent" process B does not use flock(), only fopen() to create a new file. What's the use of an exclusive lock on a file if anybody else can modify the file ? Of course, if B uses flock() as well, it raises IOError, but if not ???

By default, flock is an advisory locking mechanism. For more details, see this question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM