杀死分叉的孩子会杀死父母?

Pit*_*kos 12 c linux ipc process

我进入这种奇怪的行为,我有我的主程序和分叉的孩子.它们是这样的管道(数字是文件描述符):

 ___parent___
|            |                     ____child_____
| 0 stdin    |                    |              |
| 1 pipe1[1]----------.           |  1 stdout    |
| 2 pipe2[1]----------.\          |  2 stderr    |
|____________|         \`----------> 3 pipe1[0]  | 
                        `----------> 5 pipe2[0]  |
                                  |______________|
Run Code Online (Sandbox Code Playgroud)

所以父从stdin获取输入,但是将stdoutstderr重定向到两个管道.孩子关闭了它的标准输入并使用了管道的读取端.

然后我有一个杀死孩子的功能:

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

孩子被成功杀死但问题是父母本身也被杀死了.我检查了孩子的PID,这是正确的.

那么为什么父母会死?

rob*_*off 13

父进程在子进程退出后写入fd 1或fd 2的任何尝试都将导致内核向父进程发送SIGPIPE.SIGPIPE的默认行为是进程终止.这可能就是发生了什么.

  • 在创建管道之前@Pithikos dup()stdout/stderr.关闭管道后,dup2()再次返回文件描述符1/2. (3认同)