Last active
March 15, 2022 04:07
-
-
Save sitano/6b3e407d704ef819ccfd7cd03949e110 to your computer and use it in GitHub Desktop.
test setns
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define _GNU_SOURCE /* See feature_test_macros(7) */ | |
#include <sched.h> | |
#include <sys/syscall.h> /* Definition of SYS_* constants */ | |
#include <unistd.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <string.h> | |
#include <sys/wait.h> | |
#include <time.h> | |
static int | |
pidfd_open(pid_t pid, unsigned int flags) { | |
return syscall(__NR_pidfd_open, pid, flags); | |
} | |
int main(int argc, char **argv) { | |
struct timespec tstart={0,0}, tend={0,0}; | |
pid_t pid, child; | |
int pidfd, st; | |
if (argc < 2) { | |
printf("err: invalid num of arguments"); | |
return 1; | |
} | |
pid = (pid_t) strtol(argv[1], (char **)NULL, 10); | |
printf("moving to: %d\n", pid); | |
clock_gettime(CLOCK_MONOTONIC, &tstart); | |
pidfd = pidfd_open(pid, 0); | |
if (pidfd == -1) { | |
printf("err: bad open: %s", strerror(errno)); | |
return 1; | |
} | |
if (setns(pidfd, CLONE_NEWPID | CLONE_NEWCGROUP | CLONE_NEWIPC | CLONE_NEWNET | CLONE_NEWNS | CLONE_NEWUTS) != 0) { | |
printf("err: bad setns: %s", strerror(errno)); | |
return 1; | |
} | |
child = fork(); | |
if (child > 0) { | |
clock_gettime(CLOCK_MONOTONIC, &tend); | |
printf("waiting [fork in %ldns]\n", tend.tv_nsec-tstart.tv_nsec); | |
if (waitpid(child, &st, 0) == -1) { | |
printf("err: bad wait: %s", strerror(errno)); | |
return 1; | |
} | |
} else { | |
clock_gettime(CLOCK_MONOTONIC, &tend); | |
printf("moved in [%ldns]\n", tend.tv_nsec-tstart.tv_nsec); | |
getchar(); | |
} | |
close(pidfd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, replace pid fd with normal fd can work. And another reason as follows.
