1. 程式人生 > >如何建立一個最簡單的Linux自啟動服務?

如何建立一個最簡單的Linux自啟動服務?

最雞蛋的方法是把命令寫到/etc/rc.d/rc.local或者/etc/rc.local裡,這樣雖然能夠實現隨機執行,但是並不夠靈活。不能像mysql,apache等服務一樣能夠使用service命令或者呼叫init.d下的指令碼啟動、關閉或者重啟程序。

$ service mysql restart 
$ service apache2 stop

因為不同的Linux發行版本,對後臺服務的處理方式不大一樣,所以下面以Ubuntu系統為例,看看如何寫一個簡單的隨機自啟動服務。 

準備好一個需要隨機啟動的程式,比如:/root/auto.py,設定可執行屬性,確保可以通過輸入絕對路徑直接執行。

$ chmod +x auto.py 
$ /root/auto.py 
  It's work. 

編寫一個啟動控制指令碼,以auto為例,建立/etc/init.d/auto文字檔案,輸入下面的內容:

#!/bin/shcase "$1" instart)        start-stop-daemon --start --background --exec /root/auto.py;;stop)        start-stop-daemon --stop --name auto.pyesac

這是一個簡單的shell指令碼,case .. in是用來根據呼叫引數進行不同的操作,start-stop-daemon是一個可以管理daemon程序的程式,要檢視它的詳細說明,可以執行man start-stop-daemon

檢視。start的時候使用--exec指定要執行的檔案,stop的時候,使用--name根據程序名字來使用killall結束匹配的程序。

接著,設定指令碼檔案屬性,設定可執行標記。

$ chmod 755 /etc/init.d/auto

 這樣子,就可以使用service命令來啟動和關閉程序了。

啟動程序:

$ service proxy start
$ ps aux|grep proxy
root 353 1.4 1.9 8644 5212 ? S 09:50 0:00 /usr/bin/python /root/auto.py
root 355 0.0 0.2 1900 596 pts/0 S+ 09:50 0:00 grep --color=auto auto

關閉程序:

$ service auto stop
$ ps aux |grep auto
root 365 0.0 0.2 1900 592 pts/0 S+ 09:51 0:00 grep --color=auto auto

到這裡,一個Linux服務的程序控制指令碼已經寫好了,但是要實現隨機啟動,還需要一個步驟。
Linux開機的時候,不是直接執行/etc/init.d下的所有指令碼的,而是根據不同的runlevel來執行/etc/rc$runlevel.d下的指令碼。這裡的runlevel是用以區別系統的執行方式(例如單使用者的runlevel,多媒體桌面的runlevel,伺服器的runlevel都不同)。

在Ubuntu裡,可以使用update-rc.d來把/etc/init.d/auto安裝到各個runlevel中。更多關於update-rc.d的說明,請參見man update-rc.d

$ update-rc.d auto defaults 99 
update-rc.d: warning: /etc/init.d/auto missing LSB information 
update-rc.d: see <http://wiki.debian.org/LSBInitScripts> 
Adding system startup for /etc/init.d/auto ... 
/etc/rc0.d/K99auto -> ../init.d/auto 
/etc/rc1.d/K99auto -> ../init.d/auto 
...

update-rc.d後面有三個引數,分別是/etc/init.d下的指令碼名字,預設安裝方式,執行的優先順序。優先順序的數字越大,表示越遲執行,這裡我們把自己寫的服務放在最後執行。

如果要解除安裝隨機啟動的服務,執行

$ update-rc.d -f auto remove

在update-rc.d安裝的時候提示了警告資訊,是因為我們寫的/etc/init.d/auto太簡陋了,連LSB的資訊也沒有提供。

update-rc.d: warning: /etc/init.d/auto missing LSB information
update-rc.d: see <http://wiki.debian.org/LSBInitScripts>

只需要做一些小改動,就可以避免那個警告了。如下:

#!/bin/sh### BEGIN INIT INFO# Provides:          auto# Default-Start:     2 3 4 5# Default-Stop:      0 1 6# Short-Description: Start or stop a program.### END INIT INFOcase "$1" instart)        start-stop-daemon --start --background --exec /root/auto.py;;stop)        start-stop-daemon --stop --name auto.pyesac

到此,一個最簡單的隨機啟動服務寫好了,看起來文章挺長的,但其實也就幾個命令而已。
在下次開機啟動的時候,auto.py就會以root使用者身份被自動執行。