RasPi Boot Service

Some quick notes about starting things at boot on the RasPi, because someone asked:

Basically, you need to register your program as a system service, which can then be started at boot (and, controlled using the normal service x start/stop/restart commands).

1. Create a .service file, eg /home/pi/path/to/myprogram/myprogram.service


[Unit]
Description=My New Service
Before=systemd-user-sessions.service

[Service]
TimeoutStartSec=0

ExecStart=/path/to/program/run.sh
Type=oneshot
RemainAfterExit=yes
User=pi

ExecStop=/path/to/program/stop.sh
User=pi

[Install]
WantedBy=multi-user.target

2. I pointed the start/stop commands to shell scripts (start.sh / stop.sh) – so create those


start.sh
#!/bin/bash

cd /home/pi/piot/pi/ # Change to program's working directory
(python myprog.py & echo $! > /tmp/myprogram.pid) & # This is a double fork - it lets the command keep running in the background after the bash shell itself exits
# The echo puts the pid of the process into a temp file so we can kill it later

stop.sh
#!/bin/bash
// I haven't tested this...
kill `cat /tmp/myprogram.pid`
unlink /tmp/myprogram.pid

3. Register the service to start at boot

systemctl enable /path/to/myprogram.service

NB: kill sends a SIGTERM to the python process. This signal can be caught in order to trigger a graceful shutdown (or even ignored). If it’s not caught, the process will just be ended.

Leave a Reply

Your email address will not be published. Required fields are marked *