Peter's Notes: The /etc/rc.d/rc File

Customization of runlevels

Suppose you have something that you'd like to run whenever you start your system. Perhaps you installed xfstt or some other truetype font server and you'd like for xfstt to run whenever the system goes up so you don't have to keep typing xfstt --daemon every time you boot up. Let's take a look at the script /etc/rc.d/rc. Here are the first few lines:

#!/bin/bash
#
# rc This file is responsible for starting/stopping services when the
# runlevel changes. It is also responsible for the very first setup of
# basic things, such as setting the hostname.

it's a shell script! Let's look further.

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

The file `functions' is a shell script with a bunch of useful functions, such as:
daemon():A function to start a program.
killproc():A function to stop a program.
pidofproc():A function to find the pid of a program.
status():Gives the status of a process (running? not running? locked?)
The rest is a little technical, but here is the nuts and bolts of it.

The scripts to start in runlevel 1 are stored in /etc/rc.d/rc1.d. The scripts to start in runlevel 2 are stored in /etc/rc.d/rc2.d. The scripts to start in runlevel 3 are stored in /etc/rc.d/rc3.d. The scripts to ... well, you get the picture.

First, we create a file called /var/run/runlevel.dir which contains the name of the directory which we're going to start running scripts from. For example, if we enter runlevel 4, the file runlevel.dir will contain the text "/etc/rc.d/rc4.d". This is how programs that run on our system (like linuxconfig) learn what runlevel we're currently in.

Next we check to is if there exists a directory for the runlevel we're about to enter (pedantic yes, but necessary!).

# Is there an rc directory for this new runlevel?
if [ -d /etc/rc.d/rc$runlevel.d ]; then
# First, run the KILL scripts.
for i in /etc/rc.d/rc$runlevel.d/K*; do
# Check if the script is there.
[ ! -f $i ] && continue

# Don't run [KS]??foo.{rpmsave,rpmorig} scripts
[ "${1%.rpmsave}" != "${1}" ] && continue
[ "${1%.rpmorig}" != "${1}" ] && continue

# Check if the subsystem is already up.
subsys=${i#/etc/rc.d/rc$runlevel.d/K??}
[ ! -f /var/lock/subsys/$subsys ] && \
[ ! -f /var/lock/subsys/${subsys}.init ] && continue

# Bring the subsystem down.
$i stop
done

# Now run the START scripts.
for i in /etc/rc.d/rc$runlevel.d/S*; do
# Check if the script is there.
[ ! -f $i ] && continue

# Don't run [KS]??foo.{rpmsave,rpmorig} scripts
[ "${1%.rpmsave}" != "${1}" ] && continue
[ "${1%.rpmorig}" != "${1}" ] && continue

# Check if the subsystem is already up.
subsys=${i#/etc/rc.d/rc$runlevel.d/S??}
[ -f /var/lock/subsys/$subsys ] || \
[ -f /var/lock/subsys/${subsys}.init ] && continue

# Bring the subsystem up.
$i start
done
fi

Please report bugs or broken links to me.