Are child processes created with fork() automatically killed when the parent is killed?
60,628
No. If the parent is killed, children become children of the init process (that has the process id 1 and is launched as the first user process by the kernel).
The init process checks periodically for new children, and waits for them (thus freeing resources that are allocated by their return value).
The question was already discussed with quality answers here: How to make child process die after parent exits?
Author by
Berkyjay
Updated on January 10, 2022Comments
-
Berkyjay over 2 years
I'm creating child processes with
fork()
in C/C++.
When the parent process ends (or is killed for some reason) I want all child processes to be killed as well.
Is that done automatically by the system? Or I have to do it myself?
Pre-existing similar questions:
-
Nagabhushan Baddi over 7 yearsSo does that mean that the child processes are not abnormally killed before premature termination, but wait for them to be fully executing their code and then terminate?
-
Johannes Schaub - litb over 5 years@NagabhushanBaddi yes. Since Linux 3.4 you can make any process an "init"-process in this regard by using prctl's "PR_SET_CHILD_SUBREAPER". The process then takes children of dead processes. But if you are in a container (docker for example), you must be careful to include a proper "init" process. Dummy processes like "bash" do aswell: blog.phusion.nl/2015/01/20/… .