pidfd-util: add helper for getting our own pidfdid

let's start caching our own pidfd id, since it's somewhat involved to
get but a much better identifier for things than the classic PID is.
This commit is contained in:
Lennart Poettering
2025-01-20 21:51:29 +01:00
parent 5dc9d5b4ea
commit afede53ae9
3 changed files with 48 additions and 0 deletions
+30
View File
@@ -9,6 +9,7 @@
#include "macro.h"
#include "memory-util.h"
#include "missing_magic.h"
#include "missing_threads.h"
#include "parse-util.h"
#include "path-util.h"
#include "pidfd-util.h"
@@ -243,3 +244,32 @@ int pidfd_get_inode_id(int fd, uint64_t *ret) {
*ret = (uint64_t) st.st_ino;
return 0;
}
int pidfd_get_inode_id_self_cached(uint64_t *ret) {
static thread_local uint64_t cached = 0;
static thread_local pid_t initialized = 0; /* < 0: cached error; == 0: invalid; > 0: valid and pid that was current */
int r;
assert(ret);
if (initialized == getpid_cached()) {
*ret = cached;
return 0;
}
if (initialized < 0)
return initialized;
_cleanup_close_ int fd = pidfd_open(getpid_cached(), 0);
if (fd < 0)
return -errno;
r = pidfd_get_inode_id(fd, &cached);
if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
return (initialized = -EOPNOTSUPP);
if (r < 0)
return r;
*ret = cached;
initialized = getpid_cached();
return 0;
}
+2
View File
@@ -17,3 +17,5 @@ int pidfd_get_uid(int fd, uid_t *ret);
int pidfd_get_cgroupid(int fd, uint64_t *ret);
int pidfd_get_inode_id(int fd, uint64_t *ret);
int pidfd_get_inode_id_self_cached(uint64_t *ret);