I have a Python script that runs (infinitely) from startup in the background of a Ubuntu server. The process is ended by sending a SIGINT which is handled by the script which finishes all jobs before exiting. If anyone were to shutdown the server, thus terminating the script, important data will be lost. I was wondering if there were a way to wait for the script to finish before shutdown, or prevent shutdown altogether (if preventing it'd be nice if it could display a message).


My Python script (test.py) has a SIGINT handler where when it receives a SIGINT, it finishes all tasks before exiting. I wrote the following shell script:

PROCESS=$(pgrep -f 'python test.py')
kill -2 $PROCESS
while kill -2 $PROCESS 2> /dev/null; do
        sleep 1

This script will continuously send kill commands to the python script until it exits (it works when run). I put the script in the /etc/init.d directory, executed chmod -x on the script, made symlinks to the /etc/rc0.d and /etc/rc6.d directories with names starting with K99. Since scripts in the /etc/rc0.d//etc/rc6.d directory get run at shutdown/reboot, the script should (theoretically) run and wait until the python script finishes to shutdown/reboot. This does not seem to be working. It shutsdown/reboots without finishing the tasks.

Help would be greatly appreciated.

1 Answer 1


You linked your script to K99. When changing runlevel, the K* scripts are called with option stop, and the S* scripts are called with option start, or stop for runlevel 0 (shutdown). They are called in numerical order.

So you should remove your K99 links and replace them by K00 links so they are executed first (before the script that actually halts the system!).

  • Are processes terminated before the scripts in the rc*.d directories are executed?
    – Mocking
    Apr 19, 2016 at 0:32
  • No, but the rc scripts will do things like stop apache, unmount nfs filesystems, stop the X11 server, close the network, and so on, and these may cause your process to exit prematurely if it depends on such a connection. Depending on your version of Ubuntu, if using upstart, after all the K* scripts are run, the /etc/rc0.d/S20sendsigs starts killing jobs (with SIGTERM). With systemd it is probably more complicated.
    – meuh
    Apr 19, 2016 at 6:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.