From c6f076251033c46a66b8f06a517cd58d94ad2fb7 Mon Sep 17 00:00:00 2001 From: LoveSy Date: Tue, 9 Apr 2024 14:19:38 +0800 Subject: [PATCH] Use pidfd_open for setns which is more efficient on newer kernel --- native/src/base/misc.cpp | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/native/src/base/misc.cpp b/native/src/base/misc.cpp index 7cf725345..1bf98311d 100644 --- a/native/src/base/misc.cpp +++ b/native/src/base/misc.cpp @@ -208,16 +208,22 @@ uint32_t binary_gcd(uint32_t u, uint32_t v) { } int switch_mnt_ns(int pid) { - char mnt[32]; - ssprintf(mnt, sizeof(mnt), "/proc/%d/ns/mnt", pid); - if (access(mnt, R_OK) == -1) return 1; // Maybe process died.. + int ret = -1; + int fd = syscall(__NR_pidfd_open, pid, 0); + if (fd > 0) { + ret = setns(fd, CLONE_NEWNS); + close(fd); + } + if (ret < 0) { + char mnt[32]; + ssprintf(mnt, sizeof(mnt), "/proc/%d/ns/mnt", pid); + fd = open(mnt, O_RDONLY); + if (fd < 0) return 1; // Maybe process died.. - int fd, ret; - fd = xopen(mnt, O_RDONLY); - if (fd < 0) return 1; - // Switch to its namespace - ret = xsetns(fd, 0); - close(fd); + // Switch to its namespace + ret = xsetns(fd, 0); + close(fd); + } return ret; }