2012-08-13 119 views
3

我需要在python中创建一个守护进程。我做了搜索,发现了一块好的code。守护进程应该在系统引导后自动启动,并且应该在意外关闭时启动。我经历了Advanced programming in the Unix environment中有关守护进程的章节,并有两个问题。在python * nix系统中自动重新启动守护进程

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

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

回答

2

要创建守护进程,请使用您所找到的代码中所示的双叉()。 然后,您需要为守护进程编写一个init脚本并将其复制到/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

5

我建议你看看upstart如果你在Ubuntu上。它比inittab好,但确实涉及一些学习曲线。

编辑(作者:布莱尔):这里是我最近为自己的程序编写的新贵剧本的一个改编的例子。像这样一个基本的新贵脚本虽然(像许多这样的事情)是相当可读/可理解的,但当你开始做一些花哨的事情时它们会变得复杂。

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 
+2

我在示例脚本新贵编辑从我的项目之一,希望你不要介意。 – Blair 2012-08-13 21:40:42

+0

@Blair感谢您的有用编辑/添加。 – 2012-08-14 08:05:39

+2

如果你也使用[python-daemon](https://pypi.python.org/pypi/python-daemon/),那么请注意'expect守护进程'节最好避免 - python-daemon将会出现你正在使用暴发户,并不会双叉。 – 2013-06-19 13:21:47