From: Zbigniew Jędrzejewski-Szmek Date: Fri, 15 May 2026 08:12:00 +0000 (+0200) Subject: basic: cache the result of invoked_by_systemd() X-Git-Tag: v261-rc1~157^2~1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=601684ba950424888bde568153addabade8d4627;p=thirdparty%2Fsystemd.git 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. --- diff --git a/src/basic/argv-util.c b/src/basic/argv-util.c index c9d610b3a03..0ff2fd9bcba 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 650b00353dc..02901ebc49f 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);