Skip to content

Instantly share code, notes, and snippets.

@mrunalp
Last active August 29, 2015 14:19
Show Gist options
  • Save mrunalp/5290c92b32fe709aadd3 to your computer and use it in GitHub Desktop.
Save mrunalp/5290c92b32fe709aadd3 to your computer and use it in GitHub Desktop.
unshare and bind mount namespace
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sched.h>
#include <errno.h>
#include <sys/mount.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
if (argc < 1) {
fprintf(stderr, "Need atleast one argument");
exit(1);
}
char path[1024];
snprintf(path, 1024, "/var/run/ns/%s", argv[1]);
int ret;
ret = unshare(CLONE_NEWNS);
if (ret != 0) {
perror("unshare");
exit(1);
}
int fd = open(path, O_RDONLY|O_CREAT|O_EXCL, 0);
if (fd < 0) {
perror("open");
exit(1);
}
close(fd);
ret = mount("/proc/self/ns/net", path, "none", MS_BIND, NULL);
if (ret != 0) {
perror("mount");
exit(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment