为什么 parent.getpid() 和 child.getppid() 不同

why are parent.getpid() and child.getppid() different

我正在尝试理解过程的概念。所以我写了一个这样的程序:

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main() {
  pid_t  pid;
  pid = fork();
  if (pid == 0)
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), getppid());
  else
    printf("This is the parent process. My pid is %d and my child's id is %d.\n", getpid(), pid);
}

我预计这个程序会打印类似

的内容
This is the parent process. My pid is 2283 and my child's id is 2284.
This is the child process. My pid is 2284 and my parent's id is 2283.

但是,它会打印这个

This is the parent process. My pid is 2283 and my child's id is 2284.
This is the child process. My pid is 2284 and my parent's id is 1086.

在第二行的末尾,子进程的父pid 与父进程的pid 不同。 为什么会这样?有什么我想念的吗?

提前致谢

Tony Tannous 的暗示是正确的:child 可能比 parent 长寿。当 parent 退出时,它的 child 进程是 "hung up" 即它成为 init 进程的 child 进程。

我修改了 OP 的示例代码以强制 child 进程比 parent 进程寿命更长。

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

int main()
{
  pid_t  pid;
  pid = fork();
  if (pid == 0) {
    sleep(1); /* 1 s */
    printf(
      "This is the child process."
      " My pid is %d and my parent's id is %d.\n", getpid(), getppid());
  } else {
    printf(
      "This is the parent process."
      " My pid is %d and my child's id is %d.\n", getpid(), pid);
  }
  return 0;
}

在 cygwin 上用 gcc 编译和测试:

$ gcc -o test-pid-ppid test-pid-ppid.c

$ ./test-pid-ppid
This is the parent process. My pid is 10748 and my child's id is 10300.

$ This is the child process. My pid is 10300 and my parent's id is 1.

在我的测试中,由于特定的 PID 1(init 进程通常获得的 PID),这很明显。我对在 OP 中观察到的 PID 1086 感到有点惊讶但是:

  1. 没有规范(我知道)init 进程必须获得 PID 1 - 这只是通常情况。
  2. OP 在虚拟机上 运行。那里,可能,做的事情与平时略有不同...

关于我认为退出进程会杀死其所有 children 的信念,我进一步调查并发现:Is there any UNIX variant on which a child process dies with its parent?。简而言之:我的信念是错误的。谢谢你的提问,让我悟道。