Skip to content

Instantly share code, notes, and snippets.

@vmarmol
Created July 11, 2014 16:26
Show Gist options
  • Save vmarmol/0db2a44e1b11124130ed to your computer and use it in GitHub Desktop.
Save vmarmol/0db2a44e1b11124130ed to your computer and use it in GitHub Desktop.
Reparent Command to Init in Namespace
#include <stdlib.h>
#include <stdio.h>
#include <sched.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main() {
// NOTE: replace <pid> with PID of init, or take as an arg. This was shorter :)
// Enter namespace.
int fd = open("/proc/<pid>/ns/pid", O_RDWR);
if (fd < 0) {
printf("Failed to open NS file\n");
return 1;
}
if (setns(fd, 0) == -1) {
printf("Failed to setns()\n");
return 1;
}
// Double fork the child and sleep indefinitely.
int pid = fork();
if (pid == 0) {
pid = fork();
if (pid == 0) {
// Here we would typically exec.
while (1) {
sleep(3600);
}
}
}
return 0;
}
@glyn
Copy link

glyn commented Jul 14, 2014

@xemul - this seems to be a solution to properly re-parenting a forked process to the namespace's init. This is discussed here if you'd like to comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment