Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Killing forked child kills parent?

Tags:

c

linux

process

ipc

I am into this weird behaviour where I have my main program and a forked child. They are piped like this(the numbers are file descriptors):

 ___parent___
|            |                     ____child_____
| 0 stdin    |                    |              |
| 1 pipe1[1]----------.           |  1 stdout    |
| 2 pipe2[1]----------.\          |  2 stderr    |
|____________|         \`----------> 3 pipe1[0]  | 
                        `----------> 5 pipe2[0]  |
                                  |______________|

So parent gets input from stdin but redirects stdout and stderr to two pipes. The child has closed its stdin and uses the read ends of the pipes instead.

Then I have a function to just kill the child:

void killChild(){
  printf("Killing %d\n", (int)childID);
  fflush(stdout);
  kill(childID, SIGKILL);
  waitpid(childID, NULL, 0);   // getting rid of the zombie
}

The child gets succesfully killed but the problem is that the parent itself gets killed as well. I checked the PID of the child and it's correct.

So why does the parent die?

like image 335
Pithikos Avatar asked Nov 22 '11 13:11

Pithikos


People also ask

Does killing parent process kill child processes?

They are a collection of related processes sharing the same PGID's (Process Group ID). A common misconception is that killing the parent process will kill the children's processes too. Nevertheless, killing the parent process could allow the child processes to exist on their own.

How do you kill the parent process without killing your child?

If you are on the same terminal with the process, type ctrl-z to stop the parent, and the use ps -ef to find the PID of the php child. Use the kill lines above to effectively separate the child from the parent.

What happens when a child process exits?

When a child process terminates, some information is returned to the parent process. When a child process terminates before the parent has called wait, the kernel retains some information about the process, such as its exit status, to enable its parent to call wait later.

What is the return value of fork () in Linux if executed by child process?

Upon successful completion, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. Otherwise, -1 is returned to the parent process, no child process is created, and errno is set to indicate the error.


1 Answers

Any attempt by the parent to write to its fd 1 or fd 2 after the child exits will result in the kernel sending SIGPIPE to the parent. The default behavior for SIGPIPE is process termination. That's probably what's happening.

like image 141
rob mayoff Avatar answered Oct 03 '22 10:10

rob mayoff