Last active
June 18, 2018 18:07
-
-
Save aslrousta/b211e5ecd16bd887be33f804f3764e97 to your computer and use it in GitHub Desktop.
Process Replication
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
#include <sys/types.h> | |
#include <unistd.h> | |
/* Holds the path to the process's executable file. | |
Copied from `argv[0]` in the `main` function. */ | |
extern const char* prog_path; | |
/* Replicates the current process. */ | |
int replicate(void) | |
{ | |
pid_t pid; | |
const char* args[] = { prog_path, NULL }; | |
pid = fork(); | |
if (pid < 0) { | |
/* fork failed; `errno` can be used to indicate | |
the actual error. */ | |
return -1; | |
} | |
if (pid > 0) { | |
/* We're still in the parent process. */ | |
return 0; | |
} | |
/* Detach the child process from its parent. */ | |
setsid(); | |
execv(prog_path, args); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment