1、编写服务脚本 /root/bin/testsrv.sh,完成如下要求
(1)脚本可接受参数:start, stop, restart, status;
(2)如果参数非此四者之一,提示使用格式后报错退出;
(3)如是star,则创建/var/lock/subsys/SCRIPT_NAME, 并显示“启动成功”;考虑:如果事先已经启动过一次,该如何处理?
(4)如是stop,则删除/var/lock/subsys/SCRIPT_NAME, 并显示“停止完成”;考虑:如果事先已然停止过了,该如何处理?
(5)如是restart,则先stop,再start;考虑:如果本来没有start,如何处理?
(6)如是status,则如果 /var/lock/subsys/SCRIPT_NAME 文件存在,则显示 “SCRIPT_NAME is running…” ,如果 /var/lock/subsys/SCRIPT_NAME 文件不存在,则显示 “SCRIPT_NAME is stopped…”;
(7)在所有模式下禁止启动该服务,可用 chkconfig 和 service 命令管理。
说明:SCRIPT_NAME 为当前脚本名。
- 脚本
#!/bin/bash
#chkconfig:345 99 10
. /etc/rc.d/init.d/functions
DIR="/var/lock/subsys/"
start()
{
if [ $(status) == 1 ]
then
echo The program already start.
else
cp /etc/init.d/testsvr.sh ${DIR}
action "start sucesess."
fi
}
stop()
{
if [ $(status) == 1 ]
then
rm -f ${DIR}testsvr.sh
action "stop sucesess."
else
echo The program not start.
fi
}
restart()
{
if [ $(status) == 1 ]
then
stop
fi
start
}
status()
{
if [ -a ${DIR}testsvr.sh ]
then
echo 1
else
echo 0
fi
}
case $1 in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
status)
if [ $(status) == 0 ]
then
echo The program was stoped.
else
echo The program was started.
fi
;;
*)
echo Parameter error.
esac
- 生成服务
# 脚本第2行的内容一定要添加,否则无法加入服务
#chkconfig:345 99 10
# 复制文件及授权执行权限
[root@localhost ~]# cp testsvr.sh /etc/init.d/
[root@localhost ~]# chmod +x /etc/init.d/testsvr.sh
# 添加到服务
[root@localhost ~]# chkconfig --add testsvr.sh
# 禁止启动
[root@localhost ~]# chkconfig testsvr.sh off
# 查看设置
[root@localhost ~]# chkconfig testsvr.sh --list
testsvr.sh 0:off 1:off 2:off 3:off 4:off 5:off 6:off
- 执行结果
[root@localhost ~]# service testsvr.sh start
start sucesess. [ OK ]
[root@localhost ~]# service testsvr.sh status
The program was started.
[root@localhost ~]# service testsvr.sh start
The program already start.
[root@localhost ~]# service testsvr.sh stop
stop sucesess. [ OK ]
[root@localhost ~]# service testsvr.sh status
The program was stoped.
[root@localhost ~]# service testsvr.sh restart
start sucesess. [ OK ]
[root@localhost ~]# service testsvr.sh restart
stop sucesess. [ OK ]
start sucesess. [ OK ]