我需要当一个程序崩溃或不使用Python和重新启动它运行来检测。我需要不必依赖蟒模块上是父进程的方法。

我考虑实现一个while循环,基本上不

ps -ef | grep process name

和当处理未找到启动另一个。也许这不是最有效的方法。我是新来的Python所以可能有,做一个Python模块本已。

有帮助吗?

解决方案

为什么不自己实现它?如守护或Debian的start-stop-daemon现有的工具更容易得到其他的东西很难说得对,运行长住服务器过程

无论如何,当您启动该服务,把它的PID在/var/run/<name>.pid,然后让你的ps命令只看该进程ID,并检查它是否是正确的过程。在Linux上,你可以简单地看/proc/<pid>/exe检查它指向正确的可执行文件。

其他提示

请不要重新初始化。您的操作系统有能力做到这一点,需要几乎没有系统资源,并一定会做的更好,更可靠的比什么可以重现。

经典Linux有/ etc / inittab中

Ubuntu已经/etc/event.d(暴发户)

OS X已的launchd

的Solaris已SMF

下面的代码检查在给定的时间间隔的给定的过程,并重新启动它。

#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()

也许你需要 http://supervisord.org

我还没有尝试过自己,但有一个 Python的系统信息模块可用于查找过程并获得关于它们的信息。 AFAIR有可用于检查正在运行的进程ProcessTable类,但它似乎并没有被很好的记录...

我会去的命令行路线(它只是更容易恕我直言)只要你只检查每两秒钟相比,不到10岁的任何系统上可用的处理资源的使用应该是无穷小量。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top