1.5.3 服务启动脚本
上节在介绍Linux运行级时,谈到在Linux启动过程中会使用K或S开头的脚本关闭或启动相关服务,那么这是怎么做到的呢?本节将通过一个脚本帮助大家理解。当然因为这里还没有讲到Shell编程的内容,所以只做非常简单的讲解。
- #!binbash
#
一个bash
脚本开始的标记,必须是用“#!binbash
”开头,含义是提示系统在运行该脚本时使用
binbash
作为执行该文件的解释器
# etcrc.d/init.d/atd
#
说明自己的绝对路径
# Starts the at daemon
#
# chkconfig: 345 95 5
#345
是说在运行级是345
的时候,默认开启atd
,也就是Start
#95
是说明当默认设置为on
的时候,运行优先级定为95
#5
是说明当默认设置为off
的时候,停止优先级定为5
# description: Runs commands scheduled by the at command at the time
# specified when at was run, and runs batch commands when the load
# average is low enough.
# processname: atd
# Source function library.
. etcinit.d/functions
#
使用“.
”命令包含文件,可以使用etcinit.d/functions
中定义的函数
# pull in sysconfig settings
[ -f etcsysconfig/atd ] && . etcsysconfig/atd
test -x usrsbin/atd || exit 0
RETVAL=0
#
# See how we were called.
#
prog="atd"
start() {
# Check if atd is already running
if [ ! -f varlock/subsys/atd ]; then
echo -n $"Starting $prog: "
daemon usrsbin/atd $OPTS && success || failure
RETVAL=$?
[ $RETVAL -eq 0 ] && touch varlock/subsys/atd
echo
fi
return $RETVAL
}
#
定义start
函数
stop() {
echo -n $"Stopping $prog: "
killproc usrsbin/atd
RETVAL=$?
[ $RETVAL -eq 0 ] && rm -f varlock/subsys/atd
echo
return $RETVAL
}
#
定义stop
函数
restart() {
stop
start
}
#
定义restart
函数,实际调用时,先执行stop
函数后执行start
函数
reload() {
restart
}
#
定义reload
函数,实际调用时,就是执行restart
函数
status_at() {
status usrsbin/atd
}
#
定义status_at
函数,实际调用时,是调用etcinit.d/functions
中定义的函数status
,
参数为usrsbin/atd
,也就是查询atd
的运行状态
case "$1" in
start)
start
;;
stop)
stop
;;
reload|restart)
restart
;;
condrestart)
if [ -f varlock/subsys/atd ]; then
restart
fi
;;
status)
status_at
;;
*)
echo $"Usage: $0 {start|stop|restart|condrestart|status}"
exit 1
esac
exit $?
exit $RETVAL
上面的脚本实际上是etcinit.d/atd中的内容,我在脚本中做了一些注释来简单讲解脚本的处理过程。当atd设置为启动时,将会在对应的etcrcX.d(X代表0~6)目录下显示:S95atd->../init.d/atd,系统根据第一个字母S判定atd需要启动,然后会调用命令etcinit.d/atd start;当atd设置为关闭时,将会在对应的etcrcX.d目录下显示:K05atd->../init.d/atd,系统根据第一个字母K判定atd需要关闭,然后调用命令etcinit.d/atd stop,这样就实现了对atd的启停控制,其他服务也是同样的原理。