[systemd-devel] Detecting when running under systemd

Peter Hoeg peter at hoeg.com
Wed Aug 17 02:00:13 UTC 2022


Hi all,

I have a small program that queries an external web API, massages the data and passes it off to something else. As I only need it to run during certain windows and I didn't want to have to bother with making sure it was alive, I am starting it using a systemd timer which is sufficiently flexible. All good and it's super nice to be able to "outsource" all that to systemd.

My question is - what is the canonical way to detect that I'm running under systemd so that I can adjust accordingly? Currently I'm checking for the existence of the "_SYSTEMD_INVOCATION_ID" environment variable in order to change the logging function as the default logger includes a timestamp which is redundant when journald is picking it up.

I'm also using LoadCredential for passing tokens but that just comes down to looking for the right file name where the CREDENTIALS_DIRECTORY variable points, so that really isn't systemd specific and there is a fallback in case that isn't set or the directory/file doesn't exist anyway.

I could of course also add a --systemd flag that toggles this but if I can do "TheRightThing(tm)" out of the box, why not.

Regards,
Peter


More information about the systemd-devel mailing list