我正在实现基于文件锁定的互斥机制。我的脚本的其他实例知道,当它们碰到一个锁定的特定文件时,它们不应该运行。如何在没有竞争条件的情况下删除锁定的(flock)文件:释放锁之前还是之后?
为了达到这个目的,我使用fcntl.flock
创建并锁定了文件。当我释放锁时,我也想清理文件,当没有进程正在运行时,它不会坐在那里指示一个旧的pid。
我的问题是,何时以及如何清理文件,特别是在什么时候可以删除它。基本上,我看到两个选项:
- 截断并删除文件上的锁被释放
- 截断之前,并删除文件上的锁被释放
后,从我的理解,每一个暴露我的应用程序到略有不同的比赛条件。什么是最佳实践,我错过了什么?
下面是一个(过分简化的)例子:
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?
也非常相关的信息:HTTP:// stacko verflow.com/q/17708885/1025391 – moooeeeep