Skip to content

Commit

Permalink
Use pidfd_open for setns
Browse files Browse the repository at this point in the history
which is more efficient on newer kernel
  • Loading branch information
yujincheng08 authored and topjohnwu committed May 19, 2024
1 parent 941a363 commit c6f0762
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions native/src/base/misc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 fd, ret;
fd = xopen(mnt, O_RDONLY);
if (fd < 0) return 1;
// Switch to its namespace
ret = xsetns(fd, 0);
close(fd);
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..

// Switch to its namespace
ret = xsetns(fd, 0);
close(fd);
}
return ret;
}

Expand Down

0 comments on commit c6f0762

Please sign in to comment.