我有一个 python 守护程序作为我的网络应用程序的一部分运行/我如何快速检查(使用 python)我的守护程序是否正在运行,如果没有,启动它?
我想这样做来修复守护程序的任何崩溃,因此脚本不必手动运行,它会在调用时自动运行,然后继续运行。
如果我的脚本正在运行,我如何检查(使用 python)?
最佳答案
在 Linux 系统上很方便的一种技术是使用域套接字:
import socket
import sys
import time
def get_lock(process_name):
# Without holding a reference to our socket somewhere it gets garbage
# collected when the function exits
get_lock._lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
try:
# The null byte (\0) means the socket is created
# in the abstract namespace instead of being created
# on the file system itself.
# Works only in Linux
get_lock._lock_socket.bind('\0' + process_name)
print 'I got the lock'
except socket.error:
print 'lock exists'
sys.exit()
get_lock('running_test')
while True:
time.sleep(3)
它是原子的,并且避免了如果您的进程收到 SIGKILL 时出现锁定文件的问题
您可以read in the documentation for socket.close
垃圾收集时套接字会自动关闭。
关于python - 检查python脚本是否正在运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/788411/