0

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 ???

MKII
  • 907
  • 11
  • 35
Eric H.
  • 1,962
  • 3
  • 20
  • 33

1 Answers1

0

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

Community
  • 1
  • 1
WGH
  • 2,941
  • 2
  • 25
  • 40