Normally the child you fork shouldn't be killed when it's parent is killed, unless you do something like: How to make child process die after parent exits?
If the parent is killed, the children become a children of the init process. You probably saw on terminal that the process returns immediately after you send KILL to parent. That's because the sub-bash is waiting only on the parent's PID. But the child is actually running elsewhere.
Here is a example to show it:
#!/usr/bin/env python
# test_parent_child_kill.py
import os
import time
def child():
print "Child process with PID= %d"%os.getpid()
time.sleep(20)
def parent():
print "Parent process with PID= %d"%os.getpid()
newRef=os.fork()
if newRef==0:
child()
else:
print "Parent process and our child process has PID= %d"%newRef
time.sleep(20)
parent()
Then within sleep period:
user@mac:/tmp|⇒ python test_parent_child_kill.py
Parent process with PID= 17430
Parent process and our child process has PID= 17431
Child process with PID= 17431
user@mac:/tmp|⇒ kill 17430
user@mac:/tmp|⇒ ps -ef | grep 17431
503 17431 1 0 9:30PM ttys000 0:00.00 /usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python test_parent_child_kill.py
So the child is actually still alive.
--Edit--
- Why when the parent is killed my program exits back to the shell?
Bash invokes the command also via folk/exec via something like this:
childPid = fork();
if (childPid == 0){
executeCommand(cmd); //calls execvp
} else {
if (isBackgroundJob(cmd)){
record in list of background jobs
} else {
waitpid (childPid);
}
}
Since from bash's point of view, the parent of your program is the child, it would return to prompt input when it returns from waitpid(childPid)
.
- Is there a way to stay within the program and continue functioning as it was but with a new parent?
It might be a bit difficult if you want to "re-attach", but it's not impossible:
Attach to a processes output for viewing
https://unix.stackexchange.com/questions/58550/how-to-view-the-output-of-a-running-process-in-another-bash-session
Reference:
http://www.cs.cornell.edu/Courses/cs414/2004su/homework/shell/shell.html