]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
process-util: add helper pidfd_get_pid()
authorLennart Poettering <lennart@poettering.net>
Wed, 30 Oct 2019 15:35:48 +0000 (16:35 +0100)
committerLennart Poettering <lennart@poettering.net>
Wed, 4 Dec 2019 09:34:26 +0000 (10:34 +0100)
It returns the pid_t a pidfd refers to.

src/basic/process-util.c
src/basic/process-util.h

index 9b6c4c31f713da377515ddf797900fe887b462ab..718a237954d6ab2f890f0937bf750d08b9986263 100644 (file)
@@ -40,6 +40,7 @@
 #include "rlimit-util.h"
 #include "signal-util.h"
 #include "stat-util.h"
+#include "stdio-util.h"
 #include "string-table.h"
 #include "string-util.h"
 #include "terminal-util.h"
@@ -1488,6 +1489,38 @@ int set_oom_score_adjust(int value) {
                                  WRITE_STRING_FILE_VERIFY_ON_FAILURE|WRITE_STRING_FILE_DISABLE_BUFFER);
 }
 
+int pidfd_get_pid(int fd, pid_t *ret) {
+        char path[STRLEN("/proc/self/fdinfo/") + DECIMAL_STR_MAX(int)];
+        _cleanup_free_ char *fdinfo = NULL;
+        char *p;
+        int r;
+
+        if (fd < 0)
+                return -EBADF;
+
+        xsprintf(path, "/proc/self/fdinfo/%i", fd);
+
+        r = read_full_file(path, &fdinfo, NULL);
+        if (r == -ENOENT) /* if fdinfo doesn't exist we assume the process does not exist */
+                return -ESRCH;
+        if (r < 0)
+                return r;
+
+        p = startswith(fdinfo, "Pid:");
+        if (!p) {
+                p = strstr(fdinfo, "\nPid:");
+                if (!p)
+                        return -ENOTTY; /* not a pidfd? */
+
+                p += 5;
+        }
+
+        p += strspn(p, WHITESPACE);
+        p[strcspn(p, WHITESPACE)] = 0;
+
+        return parse_pid(p, ret);
+}
+
 static const char *const ioprio_class_table[] = {
         [IOPRIO_CLASS_NONE] = "none",
         [IOPRIO_CLASS_RT] = "realtime",
index 5f4e174f04cb180ee1a8094cbd36e441ed04bd83..33dc87122968c415a3d7c3c4b83bdb6b83a2fa1c 100644 (file)
@@ -197,3 +197,5 @@ assert_cc(TASKS_MAX <= (unsigned long) PID_T_MAX);
                 (pid) = 0;                      \
                 _pid_;                          \
         })
+
+int pidfd_get_pid(int fd, pid_t *ret);