比较新的linux系统版本配置自定义服务的实践

158 阅读1分钟

选准备好命令文件:

root@wangwei830:/opt/bin# ll

total 16
drwxr-xr-x  2 root root 4096 Dec  2 15:32 ./
drwxr-xr-x 11 root root 4096 Dec  2 14:52 ../
-rwxr-xr-x  1 root root   61 Dec  2 14:35 a*
-rwxr-xr-x  1 root root 1132 Dec  2 15:32 weiServer*

root@wangwei830:/opt/bin# pwd

/opt/bin

root@wangwei830:/opt/bin# cat a

while true
do
echo `date` >> /tmp/wserver2.log
sleep 1
done

root@wangwei830:/opt/bin# cat weiServer

#! /bin/bash
### BEGIN INIT INFO
# Provides:          wangwei
# Required-Start:    
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start wangwei daemon at boot time
# Description:       Start wangwei daemon at boot time
### END INIT INFO
 

#start yakuake

start(){
#/root/wangwei/wstart   > /tmp/wstart.log     2>&1
#/root/wangwei/gitstart > /tmp/gitstart.log   2>&1
/opt/bin/a
}

#stop

stop(){
#/root/wangwei/wstop   > /tmp/wstop.log     2>&1
#/root/wangwei/gitstop > /tmp/gitstop.log   2>&1
echo "aaaaaa"
}

 

#show the status

status(){
#echo ""
#echo ""
#echo "检查blog服务是否正常:"
#/root/wangwei/wstat

#echo ""
#echo ""
#echo "检查gitlab服务是否正常:"
#/root/wangwei/gitstat

echo ""
echo ""
echo "检查a服务是否正常:"
ps -ef |grep '/opt/bin/a' |grep -v grep
}

 

#restart

restart(){

   stop

   start

}

#execute by input command

case "$1" in

  start)

     start

  ;;

  stop)

     stop

  ;;

  status)

     status

  ;;

  restart)

     restart

  ;;

  *)

     echo $"Usage: $0   {start|stop|status|restart}"

     exit 1

esac

再编写service服务文件:

root@wangwei830:/usr/lib/systemd/system# cat wei_serverd.service

[Unit]
Description=Wangwei
Documentation=https://prometheus.io/
After=network.target

[Service]
Type=forking
User=root
ExecStart=/opt/bin/weiServer start
ExecStop=/bin/kill -WINCH ${MAINPID}
Restart=on-failure

[Install]
WantedBy=multi-user.target

注明:

    1、这里需要用forking才能启动服务
    2、这里的停止直接用系统提供的变量比较方便,也可以自己写
    3、只要有了启动和停止,就可以systemctl restart ,但是不能systemctl reload 。
    4、使用systemctl enable设置开机启动