From 07612aab66dc771a9c7aca07c74940fb6447f3fa Mon Sep 17 00:00:00 2001 From: Mike Yuan Date: Wed, 20 Nov 2024 15:12:25 +0100 Subject: [PATCH 1/2] process-util: use our usual tristate semantics for is_main_thread() While at it, _unlikely_ is dropped, as requested in https://github.com/systemd/systemd/pull/35242#discussion_r1880096233 --- src/basic/process-util.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/basic/process-util.c b/src/basic/process-util.c index 3253a9c3fb..59dfaa07f3 100644 --- a/src/basic/process-util.c +++ b/src/basic/process-util.c @@ -1226,12 +1226,12 @@ int pid_from_same_root_fs(pid_t pid) { } bool is_main_thread(void) { - static thread_local int cached = 0; + static thread_local int cached = -1; - if (_unlikely_(cached == 0)) - cached = getpid_cached() == gettid() ? 1 : -1; + if (cached < 0) + cached = getpid_cached() == gettid(); - return cached > 0; + return cached; } bool oom_score_adjust_is_valid(int oa) { From 61263e143634db1eab916fa119f70ca15c1043db Mon Sep 17 00:00:00 2001 From: Mike Yuan Date: Thu, 28 Nov 2024 00:40:11 +0100 Subject: [PATCH 2/2] process-util: make sure we don't report ppid == 0 Previously, if pid == 0 and we're PID 1, get_process_ppid() would set ret to getppid(), i.e. 0, which is inconsistent when pid is explicitly set to 1. Ensure we always handle such case by returning -EADDRNOTAVAIL. --- src/basic/process-util.c | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/basic/process-util.c b/src/basic/process-util.c index 59dfaa07f3..c74a7e7ea4 100644 --- a/src/basic/process-util.c +++ b/src/basic/process-util.c @@ -702,15 +702,17 @@ int get_process_ppid(pid_t pid, pid_t *ret) { assert(pid >= 0); - if (pid == 0 || pid == getpid_cached()) { + if (pid == 0) + pid = getpid_cached(); + if (pid == 1) /* PID 1 has no parent, shortcut this case */ + return -EADDRNOTAVAIL; + + if (pid == getpid_cached()) { if (ret) *ret = getppid(); return 0; } - if (pid == 1) /* PID 1 has no parent, shortcut this case */ - return -EADDRNOTAVAIL; - p = procfs_file_alloca(pid, "stat"); r = read_one_line_file(p, &line); if (r == -ENOENT) @@ -724,7 +726,6 @@ int get_process_ppid(pid_t pid, pid_t *ret) { p = strrchr(line, ')'); if (!p) return -EIO; - p++; if (sscanf(p, " " @@ -733,9 +734,9 @@ int get_process_ppid(pid_t pid, pid_t *ret) { &ppid) != 1) return -EIO; - /* If ppid is zero the process has no parent. Which might be the case for PID 1 but also for - * processes originating in other namespaces that are inserted into a pidns. Return a recognizable - * error in this case. */ + /* If ppid is zero the process has no parent. Which might be the case for PID 1 (caught above) + * but also for processes originating in other namespaces that are inserted into a pidns. + * Return a recognizable error in this case. */ if (ppid == 0) return -EADDRNOTAVAIL;