3

我需要在 python 中创建一个守护进程。我确实搜索并找到了一段很好的代码。该守护程序应在系统引导后自动启动,如果意外关闭,则应启动它。我浏览了 Unix 环境中的高级编程中关于守护进程的章节,并且有两个问题。

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

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

4

2 回答 2

5

如果你在 Ubuntu 上,我建议你研究一下暴发户。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
于 2012-08-13T20:56:11.903 回答
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

于 2012-08-13T21:25:51.520 回答