Mocking
Mocking

Reputation: 1894

Prevent shutdown/reboot until background Python script finishes

Background:

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).

Attempt:

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')
echo $PROCESS
kill -2 $PROCESS
while kill -2 $PROCESS 2> /dev/null; do
        sleep 1
done

This script will continuously send kill commands to the python script until it exits (it works when run). I put the script in the init.d directory, chmod -x on the script, made symlinks to the rc0.d and rc6.d directories with names starting with K99. Since scripts in the rc0.d/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.

Upvotes: 4

Views: 1213

Answers (1)

tripleee
tripleee

Reputation: 189387

The system already sends a signal to all running processes as part of the normal shutdown sequence, but it's not a SIGHUP. Change your program to handle SIGTERM instead (or, to cover all possibilities, as well. While you're at it, maybe add SIGINT, too).

There's no need for you to add anything to the shutdown scripts; I guess the reason you could not get it to work was that the process had already been terminated by the time your script ran.

Upvotes: 1

Related Questions