*nix系统中python中的自重启守护进程

2024-06-16 11:37:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要用python创建一个守护进程。我搜索了一下,发现了一块很好的code。守护进程应该在系统引导后自动启动,如果它意外关闭,应该启动它。我浏览了Advanced programming in the Unix environment中关于守护进程的章节,有两个问题。在

为了在启动后自动运行脚本,我需要将我的守护进程脚本放到/etc/init.d中。正确吗?在

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


Tags: thein脚本environment进程init系统etc
2条回答

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

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

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

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

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

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

{a3}

如果你在Ubuntu上,我建议你去看看upstart。这比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

相关问题 更多 >