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.
This commit is contained in:
@@ -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) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user