From 298f466f159e1c1203d03c16c1ab9280b844bad5 Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Wed, 30 Oct 2019 16:35:48 +0100 Subject: [PATCH] process-util: add helper pidfd_get_pid() It returns the pid_t a pidfd refers to. --- src/basic/process-util.c | 33 +++++++++++++++++++++++++++++++++ src/basic/process-util.h | 2 ++ 2 files changed, 35 insertions(+) diff --git a/src/basic/process-util.c b/src/basic/process-util.c index 9b6c4c31f71..718a237954d 100644 --- a/src/basic/process-util.c +++ b/src/basic/process-util.c @@ -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", diff --git a/src/basic/process-util.h b/src/basic/process-util.h index 5f4e174f04c..33dc8712296 100644 --- a/src/basic/process-util.h +++ b/src/basic/process-util.h @@ -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);