我有一个python守护程序作为我的web应用程序的一部分在运行/我如何快速检查(使用python)我的守护程序是否正在运行,如果没有,启动它?
我想这样做是为了修复守护进程的任何崩溃,这样脚本就不必手动运行,它将在被调用时自动运行,然后保持运行。
如何检查(使用python)我的脚本是否正在运行?
发布于 2009-04-25 17:37:56
将一个pidfile放到某个地方(例如/tmp)。然后,您可以通过检查文件中的PID是否存在来检查进程是否正在运行。当你干净地关机时,不要忘记删除文件,并在启动时检查它。
#/usr/bin/env python
import os
import sys
pid = str(os.getpid())
pidfile = "/tmp/mydaemon.pid"
if os.path.isfile(pidfile):
print "%s already exists, exiting" % pidfile
sys.exit()
file(pidfile, 'w').write(pid)
try:
# Do some actual work here
finally:
os.unlink(pidfile)
然后,您可以通过检查/tmp/mydaemon.pid的内容是否为现有进程来检查该进程是否正在运行。Monit (上面提到的)可以为您做这件事,或者您可以编写一个简单的shell脚本来使用ps返回的代码来检查它。
ps up `cat /tmp/mydaemon.pid ` >/dev/null && echo "Running" || echo "Not running"
为了获得额外的好处,您可以使用atexit模块来确保您的程序在任何情况下都能清理它的pidfile (当被终止时,引发异常等)。
发布于 2011-10-14 01:36:27
一种在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
命令在垃圾回收时自动关闭套接字。
发布于 2015-10-10 01:55:11
https://stackoverflow.com/questions/788411
复制相似问题