Skip to content

Instantly share code, notes, and snippets.

@aseaday
Created September 19, 2017 08:18
Show Gist options
  • Save aseaday/4a4111028ff4d103c9753a3d8e32a238 to your computer and use it in GitHub Desktop.
Save aseaday/4a4111028ff4d103c9753a3d8e32a238 to your computer and use it in GitHub Desktop.
#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)
static char container_stack[STACK_SIZE];
char* const container_args[] = {
"/bin/bash",
NULL
};
int container_main(void* arg)
{
printf("Container - inside the container!\n");
// sethostname("container",10); /* 设置hostname */
// system("mount -t proc proc /proc");
execv(container_args[0], container_args);
printf("Something's wrong!\n");
return 1;
}
int main()
{
printf("Parent - start a container!\n");
/* 调用clone函数,其中传出一个函数,还有一个栈空间的(为什么传尾指针,因为栈是反着的) */
int container_pid = clone(container_main, container_stack+STACK_SIZE,
CLONE_NEWUTS | CLONE_NEWIPC | CLONE_NEWPID | CLONE_NEWNS | SIGCHLD, NULL);
/* 等待子进程结束 */
waitpid(container_pid, NULL, 0);
printf("Parent - container stopped!\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment