天天看点

linux系统创建服务,并且开机自启动

有时候我们将程序编译成二进制可执行程序,需要在系统中运行,并且开启自启动。我们可以进行如下操作:

1.在/etc/init.d目录下添加可执行脚本

例如我的一个脚本test,内容如下:

#!/bin/bash
### BEGIN INIT INFO
#
# Provides:  test
# Required-Start:   $local_fs  $remote_fs
# Required-Stop:    $local_fs  $remote_fs
# Default-Start:    2 3 4 5
# Default-Stop:     0 1 6
# Short-Description:    initscript
# Description:  This file should be used to construct scripts to be placed in /etc/init.d.
#
### END INIT PROGINFO

## Fill in name of program here.
PROG="test"
PROG_PATH="/usr/bin" ## Not need, but sometimes helpful (if $PROG resides in /opt for example).
PROG_ARGS="127.0.0.1 password /workshop1/cnc_list1" 
PID_PATH="/var/run/"

start() {
    if [ `ps -ef | grep "$PROG $PROG_ARGS" | wc -l` != "1" ]; then
        ## Program is running, exit with error.
        echo "Error! $PROG is currently running!" 1>&2
        exit 1
    else
        ## Change from /dev/null to something like /var/log/$PROG if you want to save output.
        $PROG_PATH/$PROG $PROG_ARGS 2>&1 >>/var/log/$PROG &
    pid=`ps ax | grep -i $PROG | sed 's/^\([0-9]\{1,\}\).*/\1/g' | head -n 1`

        echo "$PROG started"
        echo $pid > "$PID_PATH/$PROG.pid"
    fi
}

stop() {
    echo "begin stop"
    if [ `ps -ef | grep "$PROG $PROG_ARGS" | wc -l` == "1" ]; then
       rm -f  "$PID_PATH/$PROG.pid"
       echo "$PROG not running"
    else
       echo "kill $PROG"
       rm -f  "$PID_PATH/$PROG.pid"
       echo "$PROG stopped"
       killall -9 $PROG
       sleep 1
    fi
}

## Check to see if we are running as root first.
## Found at http://www.cyberciti.biz/tips/shell-root-user-check-script.html
if [ "$(id -u)" != "0" ]; then
    echo "This script must be run as root" 1>&2
    exit 1
fi

case "$1" in
    start)
        start
        exit 0
    ;;
    stop)
        stop
        exit 0
    ;;
    status)
        ps -ef | grep "$PROG $PROG_ARGS" | wc -l
        exit 0
    ;;

    reload|restart|force-reload)
        stop
        start
        exit 0
    ;;
    **)
        echo "Usage: $0 {start|stop|reload}" 1>&2
        exit 1
    ;;
esac      

从脚本内容可以看出,我们运行的指令其实是:

test 127.0.0.1 password /workshop1/cnc_list1

我们需要将脚本添加可执行权限:

sudo chmod 755 /etc/init.d/test

  1. 在/etc/rc.d/rc.local中添加如下内容,并且修改权限,sudo chmod 755 /etc/rc.d/rc.local,创建一个软连接sudo ln -s /etc/rc.d/rc.local /etc/rc.local,这样设置以后 可以开机自启动:
#!/bin/bash
sudo /etc/init.d/test start
exit 0      

参考链接:https://unix.stackexchange.com/questions/20357/how-can-i-make-a-script-in-etc-init-d-start-at-boot

​​

​​

​​

Update-rc.d 命令用法详解:

另外一种方式:

3.编写服务文件

sudo vim /etc/systemd/system/test.service

内容如下:

[Unit]
Description=Start up script
ConditionPathExists=/etc/rc.local

[Service]
Type=forking
ExecStart=/etc/rc.local
TimeoutSec=0
StandardOutput=tty
RemainAfterExit=yes
SysVStartPriority=99

[Install]
WantedBy=multi-user.target      
sudo systemctl daemon-reload
sudo systemctl enable test.service      

继续阅读