【背景】 在有些時間我們需要自己寫一些啟動腳本,這些腳本必須符合系統的要求,也就是init腳本。下面有一個例子,我們把它理解透了,自己寫啟動腳本也就不是什么難題了。
這是一個linux啟動腳本,redhat和centos通用
腳本如下:
#!/bin/bash
# 依Shell 腳本的編碼規范書寫腳本說明
# yum This shell script enables the yum-updates daemon
#
# Author: Jeremy Katz <katzj@redhat.com>
#
# chkconfig: 345 97 03
#
# description: This is a daemon which periodically checks for updates \
# and can send notifications via mail, dbus or syslog.
# processname: yum-updatesd
# config: /etc/yum/yum-updatesd.conf
# pidfile: /var/run/yum-updatesd.pid
#
# 在當前 Shell 中運行函數庫文件 /etc/rc.d/init.d/functions
. /etc/rc.d/init.d/functions
# 設置腳本返回值變量
RETVAL=0
# 定義 start 函數
start() {
echo -n $"Starting yum-updatesd: "
# 用 /etc/rc.d/init.d/functions 中的函數 daemon 調用守護進程 yum-updatesd
daemon yum-updatesd
# 將函數 daemon 的返回值賦予變量 RETVAL
RETVAL=$?
echo
# 如果函數 daemon 執行成功,生成鎖定文件 /var/lock/subsys/yum-updatesd
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/yum-updatesd
}
# 定義 stop 函數
stop() {
echo -n $"Stopping yum-updatesd: "
# 用 /etc/rc.d/init.d/functions 中的函數 killproc 殺死守護進程 yum-updatesd
killproc yum-updatesd
echo
# 如果函數 killproc 執行成功,刪除鎖定文件 /var/lock/subsys/yum-updatesd
[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/yum-updatesd
}
# 定義 restart 函數
restart() {
stop
start
}
# 根據調用本腳本的第一個位置參數的值執行不同的操作
case "$1" in
start)
start
;;
stop)
stop
;;
restart|force-reload|reload)
restart
;;
condrestart)
# 若服務已經啟動(鎖定文件 /var/lock/subsys/yum-updatesd存在)則重新啟動
[ -f /var/lock/subsys/yum-updatesd ] && restart
;;
status)
# 用 /etc/rc.d/init.d/functions 中的函數 status 查看守護進程 yum-updatesd 的狀態
status yum-updatesd
# 將函數 status 的返回值賦予變量 RETVAL
RETVAL=$?
;;
*)
# 對于$1的其他值顯示用法
echo $"Usage: $0 {start|stop|status|restart|reload|force-reload|condrestart}"
# 退出本腳本,并以 1 為該腳本的返回值
exit 1
esac
# 退出本腳本,并以變量 RETVAL 的值為該腳本的返回值
exit $RETVAL
本來我想對腳本加一些注釋的,我看了一下,這個腳本已經說的很清楚了,這里我就不再說明了。
腳本開關的這兩行:
# chkconfig: 345 97 03
#
# description: This is a daemon which periodically checks for updates \
這兩行是chkconfig配置服務的關鍵
其中:chkconfig里面的345代表在第3 4 5運行級別啟動這個服務 97代表啟動優先級 03代表關閉優先級
description是描述信息,呵呵