Let me begin by saying that this is not a production system and I have no intention of making it one!
I have two scripts:
/home/pi/start.sh (owned by root):
#!/bin/bash
cd "$(dirname "$0")"
/usr/bin/python3 poolMonitor.py
and /home/pi/stop.sh (owned by root):
#!/bin/bash
sudo killproc -k -n poolMonitor.py
I have the file /etc/init.d/poolMonitor (owned by root):
#!/bin/bash
### BEGIN INIT INFO
# Provides: Pool Monitor
# Required-Start: $all
# Required-Stop:
# Default-Start: 5
# Default-Stop: 6
# Starts the Pool Monitor service
### END INIT INFO
start() {
echo -n "Starting : "
/home/pi/poolMonitor/start.sh
return
}
stop() {
echo -n "Shutting down : "
/home/pi/poolMonitor/stop.sh
return
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status poolMonitor
;;
restart)
stop
start
;;
*)
echo "Usage: {start|stop|status|reload|restart[|probe]"
exit 1
;;
esac
exit $?
I installed the service in init.d like this:
sudo update-rc.d poolMonitor defaults
I can successfully run (starts and stops the web server and I am able to browse to it):
sudo /home/pi/poolMonitor/start.sh
sudo /home/pi/poolMonitor/stop.sh
sudo service poolMonitor stop
sudo service poolMonitor start
Note, due to the nature of HTTPServer, start.sh never returns. I have tried adding an ampersand at the end of the line in the start.sh file:
/usr/bin/python3 poolMonitor.py &
The problem that I am having is that it does not start after a reboot (whether the ampersand is there or not).
CodePudding user response:
Create a systemd service
To convert the script into a service, create .service file :
vi /home/pi/poolMonitor.service
Add this structure to poolMonitor.service
[Unit]
Description=Pool Monitor
After=network-online.target
[Service]
ExecStart=/usr/bin/python3 /home/pi/poolMonitor.py
WorkingDirectory=/home/pi
StandardOutput=inherit
StandardError=inherit
Restart=always
[Install]
WantedBy=multi-user.target
copy the file into /lib/systemd/system
sudo cp /home/pi/poolMonitor.service /lib/systemd/system/
Test the service
sudo systemctl start poolMonitor.service
Stop it using:
sudo systemctl stop poolMonitor.service
Enable your service to start automatically on reboot by using:
sudo systemctl enable poolMonitor.service
From now you can use:
sudo service poolMonitor status/start/stop