2012-08-13 118 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