Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing a process's parent

Tags:

c

linux

process

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?

like image 923
Aboelnour Avatar asked Oct 01 '10 18:10

Aboelnour


People also ask

How do I change parent process in Linux?

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.

Can a child process change parent process?

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.

How can I change my Pgid?

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).

What runs first parent or child process?

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.


2 Answers

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).

like image 126
Ben Voigt Avatar answered Sep 24 '22 01:09

Ben Voigt


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.

like image 29
nategoose Avatar answered Sep 24 '22 01:09

nategoose