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

时间:2017-03-04 18:27:44

标签: process fork pid

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

#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不同。 为什么会这样?有什么东西我不见了吗?

提前致谢

1 个答案:

答案 0 :(得分:1)

Tony Tannous的暗示是正确的:孩子的寿命可能比父母长。当父进程退出时,子进程被“挂起”,即它成为init进程的子进程。

我修改了OP的示例代码,以强制子进程比父进程更长寿。

#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在VM上运行。在那里,可能会有比平常略有不同的事情......
  3. 关于我相信一个退出的过程会杀死所有孩子,我进一步调查并发现:Is there any UNIX variant on which a child process dies with its parent?。简而言之:我的信念是错误的。感谢那个迫使我开心的问题。

相关问题