我有一个Python脚本,可以被Linux上的许多进程调用。 我试图确保任何时候仅允许一个实例。下面是 我想出的代码:1)在进行过程中打开一个锁定文件。 2)另一个 实例检测到此文件已打开,因此它以EBUSY退出。
不幸的是,当 进程被杀死(SIGKILL)-进程被杀死时,锁文件 未清除,因此另一个实例无法运行。有没有更好的选择 解?谢谢。
#!/usr/bin/env python3.4
import os
from time import time, sleep
import argparse
import threading
import signal
import errno
from pathlib import Path
# globals
shutdown = False
lockFile = '/var/run/tlock'
def pickWork():
rc = 0
# check if another instance is in-progress
lockDir = os.path.dirname(lockFile)
if not Path(lockDir).is_dir():
os.makedirs(lockDir, exist_ok=True)
if Path(lockFile).is_file():
print('this job in progress, try after 5 min')
return errno.EBUSY
# create lock file so as second instance fails right away.
open(lockFile, 'w')
while not shutdown:
# processReqs()
print('sleeping for 5 sec')
sleep(5) # for now
# cleanup
if Path(lockFile).is_file():
os.remove(lockFile)
return rc;
def signalHandler(signum, frame):
global shutdown
print("Received signal: {0}, graceful shutdown in progress".format(str(signum)))
shutdown = True
def argParse():
parser = argparse.ArgumentParser("Simple Test Program ")
get = parser.add_argument_group("get user input")
get.add_argument("-g", "--get", action="store_true", help="get input")
args = parser.parse_args()
if not (args.get):
parser.print_help()
return None
return args
def Start():
args = argParse()
if args is None:
print('specify args')
exit(1)
signal.signal(signal.SIGINT, signalHandler)
signal.signal(signal.SIGQUIT, signalHandler)
signal.signal(signal.SIGTERM, signalHandler)
if args.get:
#t = threading.Thread(name='pickWork', target=pickWork)
#t.start()
#t.join()
rc = pickWork()
print("EXITED with rc=", rc)
if __name__ == "__main__":
Start()