1

I saw this similar question, which says that the child process won't be automatically killed when the parent process exits. So I wrote a simple program trying to validate that:

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>

int main() {
  if (!fork()) {
    while (1) {
      printf("%d: child!\n", getpid());
      sleep(5);
    }
  }
  while (1) {
    printf("%d: parent!\n", getpid());
    sleep(1);
  }
  return  0;
}

When I ran the program, the output is like this:

8056: parent!
8057: child!
8056: parent!
8056: parent!
8056: parent!
8056: parent!

And I hit ctrl + C, expecting that the parent process will be killed but child process still around. However, after I hit ctrl + C:

  1. The program exited immediately, I was expecting that child process would still write to the terminal if it is not killed. Moreover:
  2. Neither 8056 or 8057 were shown in the process list.

Does it mean that the child process will be automatically killed when parent process exits? Or did I miss any process management details in a C program?

Changda Li
  • 123
  • 1
  • 8
  • 2
    IIRC, when you do `ctrl-c`, it sends a `SIGINT` to the parent and any child that has the same TTY/stdin. I've forgotten the _exact_ mechanism, but that's essentially it. An alternate is that `SIGINT` is sent to the process _group_ of the parent [which would include the children]. Normally, that's what you want. Hit `ctrl-c` and stop your program and all spawned children. To override this, you'd need to block `SIGINT` in the [given] child (e.g. have child do: `signal(SIGINT,SIG_IGN);` but: _Caveat emptor_ ... – Craig Estey Apr 10 '20 at 01:28
  • Or have the child process become a daemon process like [this](http://www.enderunix.org/documents/eng/daemon.php) ... which will change the process group the child is in... see section 2 of the link. – TonyB Apr 10 '20 at 01:39
  • Both approaches worked! Thanks @CraigEstey. – Changda Li Apr 10 '20 at 01:48
  • And Thanks @TonyB! – Changda Li Apr 10 '20 at 01:48
  • 1
    To actually see what happens to a child when the parent is killed, try opening another shell and typing `kill 8056`. – Nate Eldredge Apr 10 '20 at 02:47
  • 1
    Process groups, sessions, controlling terminals are all factors in where the signal is sent. The POSIX description of [General Terminal Interface](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap11.html) may help pull these divergent factors together. Note that parts of the behaviour depend on the shell you're using — does it start new processes in a new process group, for example. – Jonathan Leffler Apr 10 '20 at 02:47

0 Answers0