1

我有一个 python 脚本,我使用这段代码来守护它

        def daemonise():
            from os import fork, setsid, umask, dup2
            from sys import stdin, stdout, stderr

            if fork(): exit(0)
            umask(0) 
            setsid() 
            if fork(): exit(0)

            stdout.flush()
            stderr.flush()
            si = file('/dev/null', 'r')
            so = file('daemon-%s.out'%os.getpid(), 'a+')
            se = file('daemon-%s.err'%os.getpid(), 'a+')
            dup2(si.fileno(), stdin.fileno())
            dup2(so.fileno(), stdout.fileno())
            dup2(se.fileno(), stderr.fileno())
            print 'this file has the output from daemon%s'%os.getpid()
            print >> stderr, 'this file has the errors from daemon%s'%os.getpid()

脚本在

while True: try: funny_code(); sleep(10); except:pass;

环形。它运行了几个小时,然后意外死亡。我该如何调试这样的恶魔,错误的守护进程。

[编辑]

在不启动monit之类的进程的情况下,有没有办法在python中编写一个看门狗,它可以监视我的其他守护进程并在它们出现故障时重新启动?(谁看门狗。)

4

3 回答 3

3

你真的应该为此使用python-daemon,这是一个 为标准守护进程库实现PEP 3141的库。这样,您将确保您的应用程序在其运行的任何类型的 UNIX 下执行所有正确的操作。无需重新发明轮子。

于 2009-10-23T14:27:30.523 回答
1

你为什么要默默地吞下所有的例外?尝试查看此程序捕获了哪些异常:

while True:
    try:
        funny_code()
        sleep(10)
    except BaseException, e:
        print e.__class__, e.message
        pass

可能会发生一些意想不到的事情导致它失败,但你永远不会知道你是否盲目地忽略所有异常。

我推荐使用supervisord(用 Python 编写,非常易于使用)来进行守护进程和监控进程。在 supervisord 下运行,您不必使用您的daemonise功能。

于 2009-10-21T16:55:25.520 回答
0

我在客户中使用的是daemontools。这是一个经过验证的、经过良好测试的工具,可以运行任何守护进程。

您只需编写没有任何守护程序的应用程序即可在前台运行;然后为它创建一个daemontools服务文件夹,它会发现并从现在开始自动重启你的应用程序,每次系统重启时。

它还可以处理日志轮换等。省去了很多繁琐、重复的工作。

于 2009-10-21T10:30:29.527 回答