Monday, 10 November 2014

How to automatically start an application on boot using a Raspberry Pi

Assuming you are using Raspbian (at the time of writing using version 'September 2014')...

Create an LSB init script in the usual place
e.g.
sudo vi /etc/init.d/myinit

Note you could just copy the provided LSB script template as shown below, but this has far to much stuff in it for our purposed. Or may be just copy it and edit...
e.g.
sudo cp /etc/init.d/skeleton /etc/init.d/myinit
sudo vi /etc/init.d/myinit

Anyhow, now edit myinit as below
#!/bin/sh

### BEGIN INIT INFO
# Provides:          myinit
# Required-Start:    networking bluetooth
# Required-Stop:      
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6 
# Short-Description: myinit 
# Description:       This file is only to start / stop myinit.
### END INIT INFO

case "$1" in
  start)
    echo "starting myinit..."
    /home/me/./myinit &
    ;;
  stop)
    echo "stopping myinit..."
    pkill myinit
    ;;
  *)
    echo "Usage: /etc/init.d/myinit {start|stop}"
    exit 1
    ;;
esac
The above example LSB script will start or stop a program called myinit located in /home/me.

Probably a good place to start for understanding this file is the Debian wiki (see reference below), however I have provided a brief summary here:
  • Provides: the name of the service this script will start / stop
  • Required-Start: names of services required to be started before this service
  • Default-Start / Default-Stop: run levels for which this script is used

Next you must make sure the permission of the script are correct (the script is executable).
e.g.
sudo chmod 755 /etc/init.d/myinit

Note the ownership should already be root if the script was created as above.

Finally to enable the script on boot, the appropriate links based on the script dependencies need to be added to the /etc/init.d sub folders.
e.g.
sudo update-rc.d myinit defaults

References

https://wiki.debian.org/LSBInitScripts
http://www.linuxfoundation.org/collaborate/workgroups/lsb
http://en.wikipedia.org/wiki/Runlevel

No comments:

Post a Comment