1

I want to create a system service from a Python program. The standard way up until recently seems to have been to make a daemon; however, I've read here that systemd can make many daemons obsolete: the idea is that you can use the main process to run the system service and let systemd do the rest.

So, assuming the "cool" thing to do these days is to use the main process, then what I can't get my head around is how to handle stopping and restarting of the service gracefully (i.e. via sysctl myscript restart, etc.)

I know systemd has an ExecStop parameter which can run a command on exit, and I guess I could write a script which sets a flag in a file somewhere, and my Python program could then periodically poll this file and act accordingly. However, I imagine there is a more graceful way to do this.

So, is it possible to handle stop/restart events without a daemon when using systemd?

Sean
  • 1,346
  • 13
  • 24
  • Do you want to have a Python process running constantly that handles these event sorry, or do you just want it to start up to handle the event then terminate? – Peter Gibson Nov 06 '17 at 22:42
  • @PeterGibson: I want a Python service running constantly, but the option to stop or restart it. Does this still require a daemon? – Sean Nov 06 '17 at 22:43
  • A background service basically is a daemon. Systemd will the start the process for you and stop it via signals for `stop` and `restart`, you can handle these signals in the Python script if you need to shut down gracefully, or just ignore them if it's safe to terminate the process at any time – Peter Gibson Nov 06 '17 at 22:49
  • Take a look at this answer for how to handle the signals in a Python program https://stackoverflow.com/a/31464349/66349 – Peter Gibson Nov 06 '17 at 22:50
  • @PeterGibson: thanks! I didn't realise that systemd just sends a SIGTERM to the process to stop it. Since that's the case, I can just handle that signal like you suggested. – Sean Nov 06 '17 at 23:49

0 Answers0