Writing init.d scripts
Writing init.d script:
- The following section contains all the init info required for a deamon.
### BEGIN INIT INFO
# Provides: sample_daemon
# Required-Start: some_parent_process networking
# Required-Stop: some_parent_process networking
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: This is sample init info
# Description: This is sample init deamon
# to give an example about how to
# write a init script.
### END INIT INFO
Important things to note:
- Provides should be a unique name, across server.
- Required-Start and Required-Stop defines any dependencies to handle, before start/stop.
- Default-Start or Default-Stop: They define actions needed to be taken, at different run-levels of Linux. Here is a simple description of Linux run-levels in boot process.
- Short-Description and Description -- they're for humans.
- Next few lines. These are just to source various functions from LSB (Linux Standard Base) init.
. /lib/init/vars.sh
. /lib/lsb/init-functions
- Write your start(), stop(), restart(), reload() and any other bash functions with whatever you'd like to define.
I'm skipping this section, for brevity. However, you may refer nginx init script for a good example.
- Write a switch case defining what to do, at each command.
case "$1" in
start)
log_daemon_msg "Starting $DESC" "$NAME"
start_daemon
;;
stop)
log_daemon_msg "Stopping $DESC" "$NAME"
stop_daemon
;;
restart)
log_daemon_msg "Restarting $DESC" "$NAME"
stop_daemon
start_daemon
;;
reload|force-reload)
log_daemon_msg "Reloading $DESC configuration" "$NAME"
reload_daemon
;;
status)
status_of_proc -p $PID "$DAEMON" "$NAME" && exit 0 || exit $?
;;
rotate)
log_daemon_msg "Re-opening $DESC log files" "$NAME"
rotate_logs
log_end_msg $?
;;
*)
echo "Usage: $NAME {start|stop|restart|reload|force-reload|status|rotate}" >&2
exit 3
;;
esac
- Run the following command, to create necessary symlinks in rc. This step would activate init.d script appropriately.
update-rc.d <filename> defaults
Note: This is meant for quick reference and advancements would require you to read up further on how rc and init.d works.