【问题标题】:self restarting daemon in python in *nix system* nix系统中python中的自重启守护进程
【发布时间】:2012-08-13 20:54:05
【问题描述】:

我需要在 python 中创建一个守护进程。我确实搜索并找到了一个很好的code。该守护程序应在系统启动后自动启动,如果意外关闭,则应启动它。我浏览了Advanced programming in the Unix environment 中关于守护进程的章节,并有两个问题。

要在启动后自动运行脚本,我需要将我的守护程序脚本放到 /etc/init.d。对吗?

我应该怎么做才能重生守护进程?根据这本书,我需要在 /etc/inittab 中添加一个重生条目,但我的系统上没有 /etc/inittab。我应该自己创建吗?

【问题讨论】:

    标签: python daemon


    【解决方案1】:

    如果您使用的是 Ubuntu,我建议您查看 upstart。它比inittab 好得多,但说实话确实涉及一些学习曲线。

    编辑(由 Blair 撰写):这是我最近为自己的一个程序编写的暴发户脚本的改编示例。像这样的基本 upstart 脚本是相当可读/可理解的,但是(就像许多这样的事情一样)当你开始做一些花哨的事情时,它们会变得复杂。

    description "mydaemon - my cool daemon"
    
    # Start and stop conditions. Runlevels 2-5 are the 
    # multi-user (i.e, networked) levels. This means 
    # start the daemon when the system is booted into 
    # one of these runlevels and stop when it is moved
    # out of them (e.g., when shut down).
    start on runlevel [2345]
    stop on runlevel [!2345]
    
    # Allow the service to respawn automatically, but if
    # crashes happen too often (10 times in 5 seconds) 
    # theres a real problem and we should stop trying.
    respawn
    respawn limit 10 5
    
    # The program is going to daemonise (double-fork), and
    # upstart needs to know this so it can track the change
    # in PID.
    expect daemon
    
    # Set the mode the process should create files in.
    umask 022
    
    # Make sure the log folder exists.
    pre-start script
        mkdir -p -m0755 /var/log/mydaemon
    end script
    
    # Command to run it.
    exec /usr/bin/python /path/to/mydaemon.py --logfile /var/log/mydaemon/mydaemon.log
    

    【讨论】:

    • 我在我的一个项目中编辑了一个示例 upstart 脚本,希望你不介意。
    • 如果您也使用python-daemon,请注意最好避免使用“expect daemon”节 - python-daemon 会发现您使用的是新贵并且不会双叉。
    【解决方案2】:

    要创建守护程序,请使用您找到的代码中所示的双 fork()。 然后你需要为你的守护进程编写一个初始化脚本并将它复制到 /etc/init.d/。

    http://www.novell.com/coolsolutions/feature/15380.html

    有很多方法可以指定守护程序如何自动启动,例如 chkconfig。

    http://linuxcommand.org/man_pages/chkconfig8.html

    或者您可以为某些运行级别手动创建符号链接。

    最后你需要在服务意外退出时重新启动它。您可以在 /etc/inittab 中包含服务的重生条目。

    http://linux.about.com/od/commands/l/blcmdl5_inittab.htm

    【讨论】:

      猜你喜欢
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      相关资源
      最近更新 更多