57

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:

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
GetFree
  • 40,278
  • 18
  • 77
  • 104
  • I remember seeing similar questions. E.g. http://stackoverflow.com/questions/269494/how-can-i-cause-a-child-process-to-exit-when-the-parent-does – PolyThinker Dec 28 '08 at 05:43

1 Answers1

63

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?

Dan D.
  • 73,243
  • 15
  • 104
  • 123
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
  • So 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? – Nagabhushan Baddi Nov 24 '16 at 06:47
  • 1
    @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: https://blog.phusion.nl/2015/01/20/docker-and-the-pid-1-zombie-reaping-problem/ . – Johannes Schaub - litb Oct 13 '18 at 17:30