Skip to content

Instantly share code, notes, and snippets.

@nefanov
Created January 18, 2017 17:06
Show Gist options
  • Save nefanov/2ac56ef44e15209bfebc49c4b7f62bba to your computer and use it in GitHub Desktop.
Save nefanov/2ac56ef44e15209bfebc49c4b7f62bba to your computer and use it in GitHub Desktop.
process reparent linux
What you ask for is simply impossible. By the design of the Unix and Linux internal process management init becomes the parent of all processes whose parents die. This is because processes must have parents (also by design), and init is always there, for if init dies, the system shuts down. But beyond that there is no such thing as "re-parenting" processes.
EDIT
However: As lord.garbage pointed out, there's the arcane prctl() system call which is wicked cool and makes any program that uses it unportable. Suppose we don't care. Using the PR_SET_CHILD_SUBREAPER option it can wait() not only for its own children (as before) but also for all of their descendants, should their parents die prematurely. Thus a process using this feature can assume the role of init for its descendants. The following code is a proof of concept:
#include <sys/prctl.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
int
main (int argc, const char* const argv[], char* const envp[])
{
pid_t pid;
if (prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) < 0) {
perror("prctl");
return 4;
}
pid = fork();
if (pid < 0) {
perror("fork");
return 4;
}
if (pid == 0) {
// child
char* const argv[] = { "/usr/bin/konsole", "-e", "/bin/bash", NULL };
if (execve("/usr/bin/konsole", argv, envp) < 0) {
perror("execve");
}
}
// parent
while (1) {
pid_t wpid;
int s;
wpid = waitpid(-1, &s, 0);
if (wpid > 0) {
printf("child with pid %u has exited\n", wpid);
}
}
return 0;
}
Run some programs in the background that does not need shell attendance, exit konsole, run ps, exit the programs, and see what happens. Replace konsole by anything your heart desires.
Now, in order to achieve what you want, use the prctl() call as in the PoC and then execve() to dwm. And hope that dwm wait()s for unspecific children lest they end up as zombies.
Final note: There's still no such thing as re-parenting. I.e. you still cannot arbitrarily assign a parent to a process.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment