下面以添加一個叫做watchcat的服務為例進行說明:
1、寫一個提供給service命令使用的腳本
service 命令的使用方法一般如下
啟動:
$ service watchcat start
停止:
$ service watchcat stop
重啟:
$ service watchcat restart
所以這個watchcat腳本就需要至少接受這三個命令
大概如下:$ cat watchcat

#!/bin/bash function start_cat() { echo "cat run ..." } function stop_cat() { echo "cat stop ..." } case "$1" in start) start_cat ;; stop) stop_cat ;; restart) stop_cat start_cat ;; *) echo "Usage : start | stop | restart" ;; esac
注:這個腳本不是最終腳本,還不能作為服務使用
2、還需要讓這個腳本被 chkconfig 支持
其實這個很重要,那就是在剛剛的腳本上面添加幾行注釋,這幾行只是是用來給chkconfig使用的。也就是說,當chkconfig 看到這幾行注釋的時候,它是不會把這幾行當做注釋的。
完整的腳本如下:
1 #!/bin/bash 2 # 3 # watchcat start/stop cats 4 # 5 # chkconfig: 12345 80 90
6 # description: start/stop cats 7 # 8 ### BEGIN INIT INFO 9 # Description: start/stop cats 10 ### END INIT INFO 11
12 function start_cat() 13 { 14 echo "cat run ..."
15 } 16
17 function stop_cat() 18 { 19 echo "cat stop ..."
20 } 21
22 case "$1" in
23 start) 24 start_cat 25 ;; 26
27 stop) 28 stop_cat 29 ;; 30
31 restart) 32 stop_cat 33 start_cat 34 ;; 35 *) 36 echo "Usage : start | stop | restart"
37 ;; 38 esac
現在這個腳本算是可以正式使用了。
上面代碼的第5行是必須的,這是給chkconfig看的。
第5 行的12345是表示這個watchcat 程序是需要在系統的運行級別為1、2、3、4、5的時候都進行啟動的。80和90 的意思是在rc1.d/~rc5.d/目錄下建立S80xxxxx和K90xxxxx的鏈接文件的。
3、配置watchcat的service支持
首先給watchcat添加可執行權限:
$ chmod 775 watchcat
把腳本添加復制到/etc/init.d/目錄下
$ cp watchcat /etc/init.d/
cp: cannot create regular file `/etc/init.d/watchcat': Permission denied
$ sudo cp watchcat /etc/init.d/
此時就可以使用service進行控制了,如下:
$ service watchcat start cat run ... $ service watchcat stop cat stop ...
4、然並卵,這只是完成了手動控制的階段,還需要開機啟動
先查看一下:
$ chkconfig --list watchcat service watchcat supports chkconfig, but is not referenced in any runlevel (run 'chkconfig --add watchcat')
說我們沒有添加這個叫watchcat的服務,所以進行添加: $ chkconfig --add watchcat You do not have enough privileges to perform this operation. $ sudo chkconfig --add watchcat
檢查添加后的結果: $ chkconfig --list watchcat watchcat 0:off 1:on 2:on 3:on 4:on 5:on 6:off
這樣就完成了。
引用文獻:
http://www.cnblogs.com/jimeper/archive/2013/03/12/2955687.html
http://www.linuxidc.com/Linux/2015-01/111438.htm