user3461311 user3461311 - 2 months ago 12
Linux Question

Understand Bash init script start/stop/restart/

We can we a lot of service(bash script) under folder /etc/rc.d/init.d/. And they all look like this:

case "$1" in
start) echo "start" ;;
stop) echo "stop" ;;
restart) echo "restart" ;;
esac


I just don't understand we I boot my computer, how kernel call those startup script and pass in parameter "start"
Or when the service dies, who call script and pass in parameter "restart"

Can someone explain this to me?

Thanks in advance.

Answer

It depends on your distribution / version / configuration choices. For Debian with System V-style startup files, please have a look to http://www.debian.org/doc/debian-policy/ch-opersys.html#s-sysvinit

Roughly, each runlevel has a directory, for example /etc/rc2.d for level 2, containing symbolic links to regular files (scripts) in /etc/init.d

At some point in time, when going to level 2, the following script loop runs

for s in /etc/rc2.d/S* 
do
   $s start
done

starting the execution of all links with names starting with an S, in alphabetical order. Actually The S is followed by two digits, specifying the execution order.

Same idea for the K* files, when leaving the runlevel.

Now back to your question : this is the job of some lines in the /etc/inittab file

# The default runlevel.
id:2:initdefault:

....
# /etc/init.d executes the S and K scripts upon change
# of runlevel.
#
# Runlevel 0 is halt.
# Runlevel 1 is single-user.
# Runlevels 2-5 are multi-user.
# Runlevel 6 is reboot.

l0:0:wait:/etc/init.d/rc 0
l1:1:wait:/etc/init.d/rc 1
l2:2:wait:/etc/init.d/rc 2
...