ruk·si

Runlevels and chkconfig

Updated at 2017-01-02 20:20

A runlevel tells the mode that an operating system is running in. Each runlevel has a predefined collection of started services.

0 = System is shutting down
1 = Single-user mode
2 = Multi-user mode; no network interfaces
3 = Multi-user mode with networking; normal system boot up
4 = Undefined
5 = Multi-user mode with networking and display manager
6 = System is rebooting

Most servers lack a graphical interface and therefore starts in runlevel 3.
You can check which is the system default with `cat /etc/inittab`

chkconfig is a tool for maintaining the /etc/rc[0-6].d directory hierarchy. An service management scripts are symlinked to these directories from /etc/rc.d/init.d. Each rc directory corresponds to a specific Linux runlevel.

# Lists all services and in which modes they are started.
chkconfig --list

chkconfig has five distinct functions:

  1. adding new services for management; chkconfig --add
  2. removing services from management; chkconfig --del
  3. listing the current startup information for services; chkconfig --list
  4. changing the startup information for services; chkconfig --levels
  5. checking the startup state of a particular service; chkconfig --list

Initializable services are stored in /etc/rc.d/init.d as scripts. Some installers create init script for you but frequently you need to create it yourself.

Init scripts should have 2 commented lines near the top of the script.

# chkconfig: 2345 20 80
# description: Explain what this service does

Script should be started in runlevels 2, 3, 4 and 5.
Script start priority should be 20.
Script stop priority should be 80.

Example of a simple init script, vim /etc/rc.d/init.d/my-cmd:

#!/bin/sh
# This part of the comment doesn't really matter, write anything you want.
#
# chkconfig: 345 80 20
# description: Explain what is this service.

. /etc/rc.d/init.d/functions

name="my-cmd"
cmd="/usr/bin/$name"
pid_file="/var/run/$name.pid"

[ -f $cmd ] || exit 1

RETVAL=0

start() {
    echo "Starting $name"
    $cmd
    RETVAL=$?
    return $RETVAL
}

stop() {
    echo "Stopping $name"
    kill `cat $pid_file`
    RETVAL=$?
    return $RETVAL
}

case "$1" in
    start)
        start
        ;;

    stop)
        stop
        ;;

    restart)
        stop
        start
        ;;
esac

exit $RETVAL

And then you register this script with:

chkconfig --add my-cmd
chkconfig --levels 0123456 my-cmd off
chkconfig --levels 345 my-cmd on
chkconfig --list my-cmd
chmod +x /etc/rc.d/init.d/my-cmd
service my-cmd start

Sources