Raspberry Pi service startup scripts

Sometimes you want to run your own scripts or tools on a Raspberrry Pi a service or daemon . That is a program running in the background which is usually automatically started when Linux boots and which is shut down when Linux shuts down.

The idea is to put a shell script to the directory /etc/init.d which can start and stop your daemon. This script accepts standard command line options like start, stop, restart (restart the service by stoping and then starting it) and reload (reload and apply the configuration while the service keeps running). Then you tell the system to set up everything to call the script with the right parameter during boot or shutdown.

Now the Details

First you create a script in the directory /etc/init.d with the following content and adapt it to your needs:

#! /bin/sh
### BEGIN INIT INFO
# Provides:
# Required-Start:    $all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Manage my cool stuff
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/bin

. /lib/init/vars.sh
. /lib/lsb/init-functions
# If you need to source some other scripts, do it here

case "$1" in
  start)
    log_begin_msg "Starting my super cool service"

    # do something, start the service

    log_end_msg $?
    exit 0
    ;;
  stop)
    log_begin_msg "Stopping the coolest service ever unfortunately"

     # do something to kill the service or cleanup or nothing

    log_end_msg $?
    exit 0
    ;;
  *)
    echo "Usage: /etc/init.d/ {start|stop}"
    exit 1
    ;;
esac

You can see in the header of the script some structured comments which describe the script, its runlevels for start and stop and its dependencies to other services. If you have no special dependencies (like e.g. networking, a database service, etc.) you can keep everything at the default values.

After adapting the script and saving it in /etc/init.d, you change to the /etc/init.d directory and then call

update-rc.d MyServiceScript defaults

You can take a look at other scripts in the /etc/init.d directory for inspiration how to exactly deal with starting or stopping the service.

Update: Just found a page in the scphillips blog explaining this in a much more detailed way. So perhaps have a look there, too.

LinkedIn logo mail logo