linux设置自动运行服务程序


开机运行服务脚本内容

#!/bin/sh
#
# demo_name init script
#

### BEGIN INIT INFO
# Provides:          demo_name
# Required-Start:    $syslog
# Required-Stop:     $syslog
# Should-Start:      $local_fs
# Should-Stop:       $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Monitor for demo_name activity
### END INIT INFO

# **NOTE** bash will exit immediately if any command exits with non-zero.
set -e

PACKAGE_NAME=demo_name
PACKAGE_DESC="demo_name py_script server"
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:${PATH}

start() {
    echo -n "Starting ${PACKAGE_DESC}: "
    if [ ! -d /etc/logrotate.d ]; then
        nohup /usr/bin/env python2.7 py_script.py 2>&1 | grep --line-buffered -v "INFO -" | /usr/bin/logger -t ${PACKAGE_NAME} &
    else
        if [ ! -f /etc/logrotate.d/demo_name ]; then
            cat > /etc/logrotate.d/demo_name <<EOF
/var/log/demo_name.log {
    daily
    rotate 7
    size=100k
    compress
    missingok
    notifempty
    nocreate
    postrotate
    service demo_name restart
    endscript
}
EOF
        fi
        nohup /usr/bin/env python2.7 py_script.py 2>&1 | grep --line-buffered -v "INFO -" >> /var/log/demo_name.log &
    fi
    echo "${PACKAGE_NAME}."
}

stop() {
    echo -n "Stopping ${PACKAGE_DESC}: "
    kill -9 `ps aux | grep 'python2.7 py_script.py' | grep -v grep | awk '{print $2}'` >/dev/null 2>&1 || true
    echo "${PACKAGE_NAME}."
}

restart() {
    stop || true
    sleep 1
    start
}

usage() {
    N=$(basename "$0")
    echo "Usage: [sudo] $N {start|stop|restart}" >&2
    exit 1
}

if [ "$(id -u)" != "0" ]; then
    echo "please use sudo to run ${PACKAGE_NAME}"
    exit 0
fi

# `readlink -f` won't work on Mac, this hack should work on all systems.
cd $(python -c "import os; print os.path.dirname(os.path.realpath('$0'))")

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    #reload)
    restart | force-reload)
        restart
        ;;
    *)
        usage
        ;;
esac

exit 0

设置服务:

chmod +x /opt/demo_name/demo_name.sh
/bin/ln -sf /opt/demo_name/demo_name.sh /etc/init.d/demo_name


# debian|ubuntu
which update-rc.d && update-rc.d demo_name defaults

# centos
which chkconfig && chkconfig demo_name on



常见错误:service XXX does not support chkconfig

在脚本的开头#!/bin/sh后面添加下面两行即可

#chkconfig: - 85 15
#description: This is a sample.

Archives