Created
July 14, 2016 07:07
-
-
Save qxj/8ea9729691a5b734a713cc3a72b0bac2 to your computer and use it in GitHub Desktop.
Linux namespace learning demo, to better understand docker tech. http://yuedu.baidu.com/ebook/d817967416fc700abb68fca1
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
/* LXC demo: | |
* 1. UTC, isolate hostname | |
* 2. IPC, pipe | |
* 3. PID, chroot process tree | |
* 4. NS, mount /proc to make `top` works well | |
* 5. NET, veth from OpenVZ | |
*/ | |
#define _GNU_SOURCE | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#include <stdio.h> | |
#include <sched.h> | |
#include <signal.h> | |
#include <unistd.h> | |
#define STACK_SIZE (1024*1024) | |
/* IPC */ | |
int checkpoint[2]; | |
static char child_stack[STACK_SIZE]; | |
char* const child_args[] = { "/bin/bash", NULL }; | |
int child_main(void* arg) { | |
char c; | |
close(checkpoint[1]); | |
printf(" - [%5d] World !\n", getpid()); | |
/* UTS */ | |
sethostname("In Namespace", 12); | |
/* NS */ | |
mount("proc", "/proc", "proc", 0, NULL); | |
/* IPC */ | |
read(checkpoint[0], &c, 1); | |
/* NET */ | |
system("ip link set lo up"); | |
system("ip link set veth1 up"); | |
system("ip addr add 169.254.1.2/30 dev veth1"); | |
execv(child_args[0], child_args); | |
printf("Ooops\n"); | |
return 1; | |
} | |
int main() { | |
/* IPC */ | |
pipe(checkpoint); | |
printf(" - [%5d] Hello ?\n", getpid()); | |
int child_pid = clone(child_main, child_stack + STACK_SIZE, | |
CLONE_NEWUTS | /* UTS */ | |
CLONE_NEWIPC | /* IPC */ | |
CLONE_NEWPID | /* PID */ | |
CLONE_NEWNS | /* NS */ | |
CLONE_NEWNET | /* NET */ | |
SIGCHLD, NULL); | |
/* NET */ | |
char* cmd; | |
asprintf(&cmd, "ip link set veth1 netns %d", child_pid); | |
system("ip link add veth0 type veth peer name veth1"); | |
system(cmd); | |
system("ip link set veth0 up"); | |
system("ip addr add 169.254.1.1/30 dev veth0"); | |
free(cmd); | |
/* IPC */ | |
close(checkpoint[1]); | |
waitpid(child_pid, NULL, 0); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment