1
0
mirror of https://github.com/systemd/systemd.git synced 2025-03-31 14:50:15 +03:00

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 2024-11-18 11:23:07 +01:00
parent 5dc9d5b4ea
commit afede53ae9
3 changed files with 48 additions and 0 deletions

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;
}

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);

View File

@ -28,6 +28,7 @@
#include "missing_syscall.h"
#include "namespace-util.h"
#include "parse-util.h"
#include "pidfd-util.h"
#include "process-util.h"
#include "procfs-util.h"
#include "rlimit-util.h"
@ -1065,6 +1066,21 @@ TEST(pidref_from_same_root_fs) {
ASSERT_OK_ZERO(pidref_from_same_root_fs(&child2, &self));
}
TEST(pidfd_get_inode_id_self_cached) {
int r;
log_info("pid=" PID_FMT, getpid_cached());
uint64_t id;
r = pidfd_get_inode_id_self_cached(&id);
if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
log_info("pidfdid not supported");
else {
assert(r >= 0);
log_info("pidfdid=%" PRIu64, id);
}
}
static int intro(void) {
log_show_color(true);
return EXIT_SUCCESS;