2

So the following function should be called to kill the parent process. But it leaves the child processes alive. I know you can pass a argument to the sigkill in shell command to kill all the child process under this process group. But how to do this in C?

kill(parent, SIGKILL);
underscore_d
  • 6,309
  • 3
  • 38
  • 64
J.R.
  • 769
  • 2
  • 10
  • 25
  • How could it leave its child process open? You must be overlooking something. Maybe they are in background? – marekful Jan 31 '18 at 11:39
  • @marekful Hi. If you kill the parent process with this function in c/c++, the child process still runs forward. – J.R. Jan 31 '18 at 11:44
  • That is weird. So when I kill a process from shell in Linux and children are killed automatically, who kills the children? The Kernel? – marekful Jan 31 '18 at 11:46
  • I do not know why that happened to you...you can try to run two process, all of them just print in ifinite loop. Try to kill the parent, the child is still there – J.R. Jan 31 '18 at 11:49

1 Answers1

4

You can send a signal to a process group by kill(a_negative_number, a_signal), or killpg().

See kill(2) for detail. Basically, when you fork() or execve(), the child process will have the same PGID(process group id).

Another way is to install a signal handle for the parent process. When a signal is received at the parent, parent send signal to it's children and kill them. See signal(2)

llllllllll
  • 16,169
  • 4
  • 31
  • 54
  • 6
    Be aware though, that this will likely also kill more than the target process and its child processes. All of the parent process, its other children, and the entire process tree up to something like the originating login session are likely in the same process group. The [`setsid()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/setsid.html), [`setpgid()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/setpgid.html) or [`setpgrp()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/setpgrp.html) functions can be used to create a new process group. – Andrew Henle Jan 31 '18 at 11:51