Skip to content

Instantly share code, notes, and snippets.

@aslrousta
Last active June 18, 2018 18:07
Show Gist options
  • Save aslrousta/b211e5ecd16bd887be33f804f3764e97 to your computer and use it in GitHub Desktop.
Save aslrousta/b211e5ecd16bd887be33f804f3764e97 to your computer and use it in GitHub Desktop.
Process Replication
#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