Last active
May 28, 2022 18:41
-
-
Save vitorfhc/1370406cd69231c683c59348ba51b652 to your computer and use it in GitHub Desktop.
This file contains 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
#define _GNU_SOURCE | |
#include <sched.h> | |
#include <sys/syscall.h> | |
#include <unistd.h> | |
#include <stdio.h> | |
#include <sys/types.h> | |
#include <stdlib.h> | |
#include <sys/wait.h> | |
#include <errno.h> | |
#include <string.h> | |
#include <sys/mount.h> | |
// run_child is ran by the child process when it is created. | |
int run_child(void *arg) | |
{ | |
char *filename = (char *)arg; | |
char *argv[] = {filename, NULL}; | |
int exec_ret = execv(filename, argv); | |
if (exec_ret == -1) | |
{ | |
printf("execv failed: %s\n", strerror(errno)); | |
exit(1); | |
} | |
return 0; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
// allocates 1MB of stack for the child | |
void *pchild_stack = malloc(1024 * 1024); | |
if (pchild_stack == NULL) | |
{ | |
printf("Failed to allocate stack for child\n"); | |
return -1; | |
} | |
if (argc < 2) | |
{ | |
printf("Usage: %s <command>\n", argv[0]); | |
return -1; | |
} | |
// clones the process | |
pid_t pid = clone( | |
run_child, // function to run in the child | |
pchild_stack + 1024 * 1024, // stack pointer | |
CLONE_NEWPID | CLONE_NEWNS | SIGCHLD, // unshare the PID namespace (CLONE_NEWPID) | |
argv[1]); // argv[0] is the filename | |
if (pid == -1) | |
{ | |
printf("Failed to clone process: %s\n", strerror(errno)); | |
return -1; | |
} | |
// waits for the child to finish | |
wait(NULL); | |
// frees the stack | |
free(pchild_stack); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment