Make a Linux service auto start

· Read in about 2 min · (298 Words)

Steps

  1. Create a service script in /etc/init.d/ and chmod a+x for it.
  2. Test, sudo service xxxxx start
  3. At last, sudo systemctl enable xxxxx

Different cases of the applications

1) For applications supporting daemon mode. Notice configuration of chkconfig

#!/bin/sh
# chkconfig: - 85 15
# description: shadxxxxx
# processname: shadxxxxx
# config: /etc/shadxxxxx.json
# pidfile: /var/run/shadxxxxx.pid

start(){
       shadxxxxx -c /etc/shadxxxxx.json -d start
}

stop(){
        shadxxxxx -c /etc/shadxxxxx.json -d stop
}

case "$1" in
start)
        start
        ;;
stop)
        stop
        ;;
reload)
        stop
        start
        ;;
*)
        echo "Usage: $0 {start|reload|stop}"
        exit 1
        ;;
esac

2) For applications not supporting daemon mode, you have to use daemon

#!/bin/sh
# chkconfig: - 85 15
# description: Nginx is an HTTP(S) server, HTTP(S) reverse \
# proxy and IMAP/POP3 proxy server
# processname: nginx
# config: /etc/nginx/conf.d/default.conf
# pidfile: /var/run/nginx.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

perlfastcgi="/usr/bin/perl-fastcgi.pl"
prog=$(basename perl)

lockfile=/var/lock/subsys/perl-fastcgi

start() {
    [ -x $perlfastcgi ] || exit 5
    echo -n $"Starting $prog: "
    daemon $perlfastcgi
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    stop
    start
}

reload() {
    echo -n $§Reloading $prog: §
    killproc $nginx -HUP
    RETVAL=$?
    echo
}

force_reload() {
    restart
}
rh_status() {
    status $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
        exit 2
    esac