Skip to content

Instantly share code, notes, and snippets.

@gdamjan
Created March 7, 2011 12:40
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gdamjan/858453 to your computer and use it in GitHub Desktop.
Save gdamjan/858453 to your computer and use it in GitHub Desktop.
a small C program to start a process in a Linux namespace
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int child(void *args)
{
printf("pid as seen in the child: %lu\n", (unsigned long)getpid());
// unmount all
// chroot (bind mount/pivot root dance)
// mount /proc (make /dev?)
// remove capabilities? or switch user
spawn_bash();
}
int spawn_bash(void)
{
char *newargv[] = { "/bin/bash", NULL };
execv("/bin/bash", newargv);
perror("exec");
exit(EXIT_FAILURE);
}
int main()
{
int namespaces = CLONE_NEWUTS|CLONE_NEWPID|CLONE_NEWIPC|CLONE_NEWNS|CLONE_NEWNET;
pid_t p = clone(child, malloc(4096) + 4096, SIGCHLD|namespaces, NULL);
if (p == -1) {
perror("clone");
exit(1);
}
printf("child pid: %lu\n", p);
waitpid(p, NULL, 0);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment