Skip to content

start stop daemon

Frank Bauernöppel edited this page Mar 20, 2017 · 20 revisions

It is assumed that sysvinit is used. If you are using systemd, see systemd.

Lets take the example GPIO toggling a LED. Create and edit a new file led_blinking.sh:

#! /bin/sh

# signal handler containing termination code
trap "echo 18 > /sys/class/gpio/unexport; exit" 1 2 9 15

# initialization code 
echo 18 > /sys/class/gpio/export
echo out > /sys/class/gpio/gpio18/direction 

# main loop
while :
do  
  echo 1 > /sys/class/gpio/gpio18/value
  sleep 1
  echo 0 > /sys/class/gpio/gpio18/value
  sleep 1
done

It is possible to run led_blinking.sh from a shell provided that it is executable (chmod +x led_blinking.sh):

root@raspberrypi3:~# ./led_blinking.sh

But, this has several disadvantages:

  • the shell is blocked while the main start-stop-daemon loop is running
  • you need to login to start the loop
  • the script ends when you logout

It is possible to start led_blinking.sh as a backgound job (by appending a & to the command, but a better solution is to daemonize it:

root@raspberrypi3:~# start-stop-daemon --start --background --pidfile /var/run/led_blinking.pid --make-pidfile --exec ./led_blinking.sh

to stop it, use:

root@raspberrypi3:~# start-stop-daemon --stop --pidfile /var/run/led_blinking.pid

The pidfile contains the process id (PID), try cat var/run/lled_blinking.pid to see it. This can be conveniently used to identify the running process and to check if it is running.

further steps

Using start-stop-daemon can be combined with autostart to create a program that will be executed whenever Linux is running:

  • on start, the autostart script will spawn a daemon doing the real work as described above.
  • on stop, start-stop-daemon tries to kill the script which will trigger the termination code.

start-stop-daemon has much more interesting options, search for man start-stop-daemon.

Clone this wiki locally