我正在尝试为运行在集群上的软件实现一个基于文件系统的锁。底层共享文件系统是使用DRBD实现的,因此可以认为同步是有保证的。我当前的实现如下所示:
# check the lock file
if os.path.isfile(lockfile):
if time.time() - os.path.getmtime(lockfile) > 3600:
logInfo('lock is older than 3600s, removing it and going on collecting result.')
os.remove(lockfile)
else:
logInfo('Previous action is still on-going, please wait until it\'s finished or timeout.')
sys.exit(1)
# create the lock file
open(lockfile, 'w').close();显然,当运行在集群中不同机器上的脚本的多个实例可能一致地认为系统未锁定、创建锁定文件并执行需要互斥的操作时,可能会发生这种情况。
因此,总而言之,我需要一个基于文件系统的锁定工具,锁检查和创建一起形成一个原子操作。
使用lockfile命令可以在shell脚本中实现相同的功能。
发布于 2016-08-23 17:18:45
可以通过使用包装open系统调用的os.open来实现解决方案:
import os,errno
def lockfile(filename):
try:
os.close(os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY));
except OSError as e:
if e.errno == errno.EEXIST: # System is already locked as the file already exists.
return False
else: # Something unexpected went wrong so reraise the exception.
raise
return True # System has successfully been locked by the function注意os.open()的第二个参数。根据this answer的说法,当将标志O_EXCL与O_CREAT一起使用时,并且路径名已经存在,那么open()将失败,或者更准确地说,将引发带有errno EEXIST的OSError,这在我们的例子中意味着系统已经被锁定。但是,当路径指向一个不存在的文件时,它将被立即创建,而不会为文件系统的其他用户同时执行相同的步骤留下时间范围。根据this one的说法,所描述的技术可以被认为是广泛的平台无关性。
https://stackoverflow.com/questions/39040174
复制相似问题