user3461311 user3461311 - 1 year ago 143
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" ;;

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 Source

It depends on your distribution / version / configuration choices. For Debian with System V-style startup files, please have a look to

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* 
   $s start

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.

# /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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download