Skip to content

Instantly share code, notes, and snippets.

@daTokenizer
Created January 21, 2020 02:33
Show Gist options
  • Save daTokenizer/7d6631d50d2cd1953a0a057bd2f603e6 to your computer and use it in GitHub Desktop.
Save daTokenizer/7d6631d50d2cd1953a0a057bd2f603e6 to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#define STACK_SIZE (1024 * 1024)
static char child_stack[STACK_SIZE];
static int metrics_fn() {
printf("child PID: %ld\n", (long)getpid());
printf("parent PID: %ld\n", (long)getppid());
printf("New `net` Namespace:\n");
system("ip link");
printf("\n\n");
return 0;
}
void* unshare_fn(int flags, void* fn) {
unshare(flags);
return fn;
}
int run_child(char* msg, void* fn, int flags){
printf(msg);
pid_t child_pid = clone(fn, child_stack+STACK_SIZE, flags, NULL);
printf("clone() = %ld\n", (long)child_pid);
waitpid(child_pid, NULL, 0);
}
int main() {
printf("=== PARENT ===\n");
metrics_fn();
run_child("=== JUST CLONE ===\n", metrics_fn, SIGCHLD);
run_child("=== NEW PID ===\n", metrics_fn, CLONE_NEWPID | SIGCHLD);
run_child("=== NETWORK ===\n", metrics_fn, CLONE_NEWNET | SIGCHLD);
run_child("=== UNSHARE ===\n", unshare_fn(CLONE_NEWNET | CLONE_NEWCGROUP | CLONE_NEWPID, metrics_fn), SIGCHLD);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment