IMG_20140227_153628

Starting Scripts on Start-up – Wind Speed Sensor

Cron is great for starting normal scripts on startup, but scripts that require sudo (administrator / superuser privileges) need to be run in a different way. During my dissertation, I found that init.d scripts can be used to easily start other scripts on boot, even ones requiring superuser access (e.g ones that access Pi hardware, like the GPIO pins).

a0-windspeedsensor.sh init.d script:

#! /bin/sh
# /etc/init.d/a0-windspeedsensor.sh

### BEGIN INIT INFO
# Provides: a0-windspeedsensor
# Required-Start: $remote_fs $syslog $all
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start wind speed sensor script
# Description: Start wind speed sensor script
### END INIT INFO

# If you want a command to always run, put it here

# Carry out specific functions when asked to by the system
case “$1″ in
start)
echo “Starting windspeed.py script”
# run application you want to start
/usr/bin/python /var/www/windspeed.py &
;;
stop)
echo “Killing windspeed.py”
# kill application you want to stop
PROCESSID=$(sudo ps aux | grep “/usr/bin/python” | grep “windspeed.py” | awk ‘{print $2}’ | awk “NR==1″); sudo kill -9 $PROCESSID
;;
*)
echo “Usage: /etc/init.d/a0-windspeedsensor.sh {start|stop}”
exit 1
;;
esac

exit 0

Explanation:

The first section is the init.d information, specifying what the script provides, and that it should be ran after all other scripts ($all).  It also specifies on which run levels the script will be started and stopped (e.g start when booting in all modes, stop when shutting down/rebooting etc).

In the start case, the windspeed python script is started, in the background. In the stop case, the process ID is found for the running script, and is then killed.

The script is named a0-…. so that it will run first before any other script that I create, which will be named a1, a2… as the scripts run in alphabetical order. This just keeps things tidy and running in a known order.

This script is placed into /etc/init.d/ then registered with the update-rc.d command e.g: sudo update-rc.d a0-windspeedsensor.sh defaults. This will create relevant symbolic links in the relevant rc.d start up and shut down folders, so that the script will start on boot automatically. The permissions need to be set to 755 on the init.d script: sudo chmod 755 a0-windspeedsensor.sh.

Give it a test, and you’re good to go!

Matt