Handling restart signal


I have a working python snap.
It has 2 threads and they share a Queue in a persistent disk file.

If snap gets refreshed, it will be stopped and started, which might cause data loss (at least of 1 element…).

What is the proper way to handle the snap stop signal (in python if possible…)?
I want to stop all working operations (data write, queue get() and put()) before having it killed…


It looks like you are running a service them. Have you tried the metadata for handling start-stop?

See the following post for details on refresh-mode and stop-mode:

You’ll ultimately want to use, eg. stop-mode: sigterm and then establish a proper handler for SIGTERM in the code.

@sirvo, I do something very similar and have it working quite nicely. As others pointed out, assuming that your python script is triggered as a systemd service (probably type “simple”), then what you need to do is handle SIGTERM within the script. There’s actually nothing specific to snapcraft here.

The way you’d need to have your script running is roughly as follows:

  • Add a handler for SIGTERM and cause it to raise SystemExit exception (see https://stackoverflow.com/a/24574672)
  • In your “producer” thread, catch the SystemExit exception and at that point put a “magic” value in the queue - something like None or {} or anything that wouldn’t occur during the normal course of execution. After putting that value in the queue the producer thread should exit.
  • In your “consumer” thread, detect the above-mentioned magic value and exit the thread. If it’s a FIFO queue, there should then be no more values left in the queue, so you’re good. If it’s LIFO you’ll have to add an extra block to ensure the rest of the values get processed also
  • Your script should then also exit once both threads have finished. systemd will pick up after this graceful exit and restart normally. I believe there is an adjustable timeout for how long systemd will wait for a graceful exit, before force-terminating.

Hope the above is helpful!


Thank you all!
It did work very good!