]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
basic: cache the result of invoked_by_systemd()
authorZbigniew Jędrzejewski-Szmek <zbyszek@amutable.com>
Fri, 15 May 2026 08:12:00 +0000 (10:12 +0200)
committerZbigniew Jędrzejewski-Szmek <zbyszek@amutable.com>
Fri, 15 May 2026 08:49:37 +0000 (10:49 +0200)
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
src/basic/argv-util.h

index c9d610b3a037d0458649e526a2df47214cf02cf6..0ff2fd9bcbaaf0533a5b1e48515823b8dc68fc26 100644 (file)
@@ -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) {
index 650b00353dc0894ab6b8f7c1f68a9b9b059291ed..02901ebc49f4b4699fd057880027d7fc53ab74d0 100644 (file)
@@ -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);