From 601684ba950424888bde568153addabade8d4627 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Zbigniew=20J=C4=99drzejewski-Szmek?= Date: Fri, 15 May 2026 10:12:00 +0200 Subject: [PATCH] basic: cache the result of invoked_by_systemd() This function is used in a quite a few places and it calls getenv and does a bit of parsing, so let's try to speed this up. Also, mark it _const_. With the caching, it now always returns the same result, so we can tell the compiler to eliminate subsequent invocations. --- src/basic/argv-util.c | 13 +++++++++---- src/basic/argv-util.h | 2 +- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/basic/argv-util.c b/src/basic/argv-util.c index c9d610b3a0..0ff2fd9bcb 100644 --- a/src/basic/argv-util.c +++ b/src/basic/argv-util.c @@ -39,27 +39,32 @@ bool invoked_as(char *argv[], const char *token) { } bool invoked_by_systemd(void) { + static int cached = -1; int r; + if (cached >= 0) + return cached; + /* If the process is directly executed by PID1 (e.g. ExecStart= or generator), systemd-importd, * or systemd-homed, then $SYSTEMD_EXEC_PID= is set, and read the command line. */ const char *e = getenv("SYSTEMD_EXEC_PID"); if (!e) - return false; + return (cached = false); if (streq(e, "*")) /* For testing. */ - return true; + return (cached = true); pid_t p; r = parse_pid(e, &p); if (r < 0) { /* We know that systemd sets the variable correctly. Something else must have set it. */ log_debug_errno(r, "Failed to parse \"SYSTEMD_EXEC_PID=%s\", ignoring: %m", e); - return false; + return (cached = false); } - return getpid_cached() == p; + cached = getpid_cached() == p; + return cached; } bool argv_looks_like_help(int argc, char **argv) { diff --git a/src/basic/argv-util.h b/src/basic/argv-util.h index 650b00353d..02901ebc49 100644 --- a/src/basic/argv-util.h +++ b/src/basic/argv-util.h @@ -9,7 +9,7 @@ extern char **saved_argv; void save_argc_argv(int argc, char **argv); bool invoked_as(char *argv[], const char *token); -bool invoked_by_systemd(void); +bool invoked_by_systemd(void) _const_; bool argv_looks_like_help(int argc, char **argv); int rename_process_full(const char *comm, const char *invocation);