my name is GYAN
my name is GYAN

Reputation: 1289

Parent death is not killing child proess in C program Linux

See the code below:

#include<stdio.h>

void main()
{
        int pid = fork();
        if(pid==0)
        {
                while(1);
        }
        else
        {
                while(1);
        }
}

Run this code from terminal 1:

Go to terminal 2, and check processes on terminal 1:

hduser@pc4:~$ ps -ft /dev/pts/1
UID        PID  PPID  C STIME TTY          TIME CMD
hduser    3824  3505  0 17:20 pts/26   00:00:00 bash
hduser    4007  3824 21 17:33 pts/26   00:00:01 ./a.out
hduser    4008  4007 22 17:33 pts/26   00:00:02 ./a.out
hduser@pc4:~$

Two a.outs running here. Now kill the parent 4007.

hduser@pc4:~$ kill -9 4007
hduser@pc4:~$ ps -ft /dev/pts/26
UID        PID  PPID  C STIME TTY          TIME CMD
hduser    3824  3505  0 17:20 pts/26   00:00:00 bash
hduser    4008  2077 24 17:33 pts/26   00:00:29 ./a.out
hduser@pc4:~$

Note 4008 is still running and it is now child of 2077(init --user).

My Doubt is:

  1. Why child is not killed by parent before parents death?
  2. Normally if we run any process from terminal(bash) without "nohup", and kill bash then child of bash is killed. How to implement this behaviour in our C program?
  3. I thought default behaviour is that parent kills its child before death, and we have to call wait() to overcome this behaviour. But i was wrong. Then what is purpose of wait()?

I am using Ubuntu 14 with 3.13.0-52-generic kernel.

Upvotes: 0

Views: 1044

Answers (2)

Sreeyesh Sreedharan
Sreeyesh Sreedharan

Reputation: 793

In linux the child process is not killed when the parent dies.

You can write a signal handler for the parent and in that signal handler you can call APIs to kill the child process.

Wait system call is invoked from the parent process to suspend it until one of its child terminates. Otherwise the child will become a zombie process.

Upvotes: 0

dbush
dbush

Reputation: 223897

On Linux / UNIX system, a process does not die unless it either exits or is explicitly killed by some other process.

What the wait system call does is suspend the process until one of its child processes dies. You can also call waitpid, which waits for a specific child process to die.

If a process has a controlling terminal and the terminal quits, any process under that controlling terminal is killed by the OS. You can use the setsid system call to detach a process from its controlling terminal so that it can live in the background even after the user logs out.

Upvotes: 2

Related Questions