Is it possible to change a process parent?
ex: parent A has Child B can I make the parent of B is the Init process without killing A?
The parent process id (ppid) of a process cannot be changed outside of the kernel; there is no setppid system call. The kernel will only change the ppid to (pid) 1 after the processes parent has terminated - if the process did not respond to a signal that the parent was terminated.
Processes have separate memory spaces. One process cannot change the memory of another process, and parent/child processes are no exception. A child cannot change a parent's variables, nor a parent its children's.
These calls are reserved to the process itself: a process cannot change another process's PGID or SID, with one exception: a process can change its children's PGID if they're still running the original process image (i.e. they haven't called execve to run a different program).
The original process is called the parent process and the second process is called the child process. The child process is an almost exact copy of the parent process. Both processes continue executing from the point where the fork( ) calls returns execution to the main program.
Not from outside of process B.
From inside process B, you can call fork which makes a copy of your process, then let the original exit. When that happens the new copy B2 will not be a child of A, its parent will be set to 1 (the init process).
Calling ptrace(PTRACE_ATTACH, pid, x, y)
where pid
is the pid of B (in your example) and x and y don't matter (probably set them to NULL) will make the calling process the parent of B for many (but not all) purposes (with restrictions based on user ID of the processes, of course, to keep you from taking over someone else's processes unless you are root).
After calling ptrace(PTRACE_ATTACH,
the child will still get either its original parent or init's pid as its parent pid from getppid()
, but the tracing process will be able to call wait
and get SIGCHLD
from process B.
There is a lot of stuff going on here, so you should read man 2 ptrace
and make sure you understand the details pretty well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With