ubuntu自定义服务模板

时间:2022-01-08 18:29:52

根据他人代码修改:

 #!/bin/sh
### BEGIN INIT INFO
# Provides: <pragram name>
# Required-Start: $local_fs $network $named $time $syslog
# Required-Stop: $local_fs $network $named $time $syslog
# Default-Start:
# Default-Stop:
# Description: shrpx proxy
### END INIT INFO PROG= #<pragram name>
PIDFILE= #<pid file full path>
LOGFILE= #<log file full path> start() {
if [ -f $PIDFILE ]; then
if ! pgrep $PROG; then
echo "Terminate abnormaly last time!"
rm -f $PIDFILE
else
echo 'Service already running' >&
return
fi
fi if [ -n "$PIDFILE" ];then
PIDFILE="&1"
fi echo 'Starting service...' if $PROG >$LOGFILE; then
echo 'Service started'
else
echo 'Start failed!' >&
fi
} stop() {
if [ ! -f "$PIDFILE" ]; then
echo 'Service not running' >&
return
fi
echo 'Stopping service…' >&
kill -KILL $(cat "$PIDFILE")
rm -f "$PIDFILE"
echo 'Service stopped' >&
} status(){
if [ -f "$PIDFILE" ];then
echo "$PROG is running"
else
echo "$PROG is stopped"
fi
} uninstall() {
echo "Are you really sure you want to uninstall this service?"\
"That cannot be undone. [yes|No] "
local SURE
read SURE
if [ X"$SURE" = "Xyes" ]; then
stop
if [ -f $PIDFILE ]; then
rm -f "$PIDFILE"
fi
echo "Notice: log file is not be removed: '$LOGFILE'" >&
update-rc.d -f $PROG remove
rm -fv "$0"
fi
} case "$1" in
start)
start
;;
stop)
stop
;;
uninstall)
uninstall
;;
retart)
stop
start
;;
status)
status
;;
*)
echo "Usage: $0 {start|stop|status|restart|uninstall}"
esac

使用方法:cp到/etc/init.d/下面,修改<>里面的内容,然后使用update-rc.d管理服务;

添加一个服务:sudo update-rc.d srv_name defaults
删除一个服务 :sudo update-rc.d–f srv_name remove

default表示的是服务的运行优先级,默认是20,数字越小优先级越高。

以后就会开机自启动了,使用sudo service srv_name start|stop|status|restart|uninstall来做临时性的管理。