Ubuntu 14.04 编写service 服务

有时我们需要将特定操作封装成服务,通过服务启动停止,例如nginx的启动停止,service nginx start 或者service nginx stop

 

下面我们将编写一个demo

cd /etc/init.d/

 

sudo vi test,建立一个service名称为test的服务

加入下面模版代码

Ubuntu 14.04 编写service 服务
#! /bin/sh
### BEGIN INIT INFO
# Provides:          reboot
# Required-Start:
# Required-Stop:
# Default-Start:
# Default-Stop:      6
# Short-Description: Execute the reboot command.
# Description:
### END INIT INFO

PATH=/sbin:/usr/sbin:/bin:/usr/bin

. /lib/lsb/init-functions

do_stop () {
# Message should end with a newline since kFreeBSD may
# print more stuff (see #323749)
log_action_msg
Will now restart
reboot
-d -f -i
}

case $1 in
start)
nohup
/etc/init.d/test.sh >> b.log 2>&1 &
;;
stop)
do_stop
;;
*)
echo
Usage: $0 start|stop >&2
exit
3
;;
esac

Ubuntu 14.04 编写service 服务

可以根据需要编写start方法以及stop方法

赋予执行权限

sudo chmod +x /etc/init.d/test

 

 

然后我们再写一个shell测试脚本

sudo vi test.sh

Ubuntu 14.04 编写service 服务
#!/bin/bash
int=1
while(( $int<=5 ))
do
    date >> ~/a.log
    sleep 1 
#   let "int++"
done
Ubuntu 14.04 编写service 服务

赋予执行权限

sudo chmod +x /etc/init.d/test.sh

 

 

 

接下来,我们启动服务

service test start

 

查看服务是否已经启动

tail -f ~/a.log

 

会看到不断的打印时间

Ubuntu 14.04 编写service 服务

 

这说明我们的脚本已经以服务的形式启动起来了。