Python中的自动重启系统
我需要用Python来检测一个程序是否崩溃或者没有运行,并且在这种情况下重新启动它。我希望找到一种方法,不一定要依赖Python模块作为父进程。
我在考虑实现一个循环,基本上是这样做的:
ps -ef | grep process name
当找不到这个进程时,它就会启动另一个。也许这不是最有效的方法。我刚开始学Python,所以可能已经有现成的Python模块可以做到这一点。
6 个回答
1
下面的代码会在指定的时间间隔内检查一个特定的程序,如果这个程序没有运行,就会重新启动它。
#Restarts a given process if it is finished.
#Compatible with Python 2.5, tested on Windows XP.
import threading
import time
import subprocess
class ProcessChecker(threading.Thread):
def __init__(self, process_path, check_interval):
threading.Thread.__init__(self)
self.process_path = process_path
self.check_interval = check_interval
def run (self):
while(1):
time.sleep(self.check_interval)
if self.is_ok():
self.make_sure_process_is_running()
def is_ok(self):
ok = True
#do the database locks, client data corruption check here,
#and return true/false
return ok
def make_sure_process_is_running(self):
#This call is blocking, it will wait for the
#other sub process to be finished.
retval = subprocess.call(self.process_path)
def main():
process_path = "notepad.exe"
check_interval = 1 #In seconds
pm = ProcessChecker(process_path, check_interval)
pm.start()
print "Checker started..."
if __name__ == "__main__":
main()
3
请不要自己重新发明初始化的过程。你的操作系统已经有现成的功能来处理这些事情,这些功能几乎不需要占用系统资源,而且肯定比你自己写的要更好、更可靠。
经典的Linux系统有一个叫做/etc/inittab的文件。
Ubuntu系统使用的是/etc/event.d(也叫upstart)。
OS X系统有一个叫launchd的工具。
Solaris系统则使用smf。
5
为什么要自己实现呢?像daemon或者Debian的start-stop-daemon
这样的工具,通常能更好地处理一些复杂的事情,比如如何正确地运行长时间运行的服务器进程。
无论如何,当你启动服务时,要把它的进程ID(pid)放在/var/run/<name>.pid
这个文件里。然后,你的ps
命令只需要查找这个进程ID,确认它是正确的进程。在Linux系统中,你可以简单地查看/proc/<pid>/exe
,来检查它是否指向正确的可执行文件。