Trying to Write a Shutdown Script
October 21st, 2008I’ve been trying to create a python script runs on shutdown or reboot. First I tried using the init system by placing the script into the /etc/init.d directory and then creating symlinks to the rc0 and rc6 directories so it runs shutdown and restart (all as root).
# cp myscript.py /etc/init.d # ln -s /etc/init.d/myscript.py /etc/rc0.d/K10myscript.py # ln -s /etc/init.d/myscript.py /etc/rc6.d/K10myscript.py
This doesn’t work, at least on Fedora, I think due to the fact that the init system checks for the presence of a file in /var/lock/subsys. Essentially the system checks whether a service is running (the lock file exists) before deciding to run the script.
In this case I would have to add my script as a service using chkconfig -add that starts on boot and creates the lock file. This is fine but what if I just want to run a simple script and not a service.
Next I looked at Upstart, the replacement for init scripts developed by Ubuntu but now the default in Fedora 9. This is compatible with the old init system but much more flexible. Following this great guide I tried to implement this using Upstart. Here’s my script saved in the /etc/event.d/ directory.
# Run my script on shutdown, reboot and runme events start on runlevel 0 # Shutdown start on runlevel 6 # Reboot start on runme # testing event script exec "/home/username/network_usage.py" end script
I tested the script by emitting the runme event.
# /sbin/initctl emit runme runme network-usage (start) waiting network-usage (start) starting network-usage (start) pre-start network-usage (start) spawned, process 3673 network-usage (start) post-start, (main) process 3673 network-usage (start) running, process 3673 network-usage (stop) running network-usage (stop) stopping network-usage (stop) killed network-usage (stop) post-stop network-usage (stop) waiting initctl: runme event failed
Basically the script fails. I tried to run a bash script that calls the python script but that also fails. Upstart seems really easy to use and it’s much easier to test since you can create fictional events but I’m frustrated by my inability to run a simple python script.
I realise that I could write a bash script instead of a python script and it will probably work, or I could put my script in .bash_logout but that would run on user logout and not only on shutdown and reboot.
If anyone has a solution I’d be happy to hear.