I am implementing a mutual exclusion mechanism based on a file lock. Other instances of my script know that they are not supposed to run when they come accross a specific file, which is locked.
In order to achieve this, I have created and locked the file using fcntl.flock
. When I release the lock I also want to clean up the file, that it doesn't sit there indicating an old pid when no process is actually running.
My question is, when and how should I clean up the file, especially at what point can I delete it. Basically I see two options:
- truncate and delete the file before the lock is released
- truncate and delete the file after the lock is released
From my understanding, each one exposes my application to slightly different race conditions. What is best practice, what have I missed?
Here's an (overly simplified) Example:
import fcntl
import os
import sys
import time
# open file for read/write, create if necessary
with open('my_lock_file.pid', 'a+') as f:
# acquire lock, raises exception if lock is hold by another process
try:
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print 'other process running:', f.readline()
sys.exit()
try:
# do something
f.write('%d\n' % os.getpid())
f.flush()
# more stuff here ...
time.sleep(5)
finally:
# clean up here?
# release lock
fcntl.flock(f, fcntl.LOCK_UN)
# clean up here?
# clean up here?