【问题标题】:why are parent.getpid() and child.getppid() different为什么 parent.getpid() 和 child.getppid() 不同
【发布时间】:2017-03-04 18:27:44
【问题描述】:

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

#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 与父进程的进程进程 ID 不同。 为什么会这样?有什么我遗漏的吗?

提前致谢

【问题讨论】:

  • 我测试了您的样本,无法重现您描述的行为。在我的系统上,它可以按照您(和我)的期望工作。我有 Windows 10、cygwin、gcc 5.4.0。奇怪...
  • 我也在coliru 上测试过它。相同的结果 - 它按预期工作。
  • 我在 Oracle VM Ubuntu 上运行这个程序。是不是因为它而发生?
  • 我认为这是因为父进程在子进程调用 getppid() 之前终止。
  • 这是因为父进程首先终止,然后子进程被分配为 init 进程的子进程,它在您的操作系统上的 pid 可能是 1086

标签: process fork pid


【解决方案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 上运行。那里的事情可能与平时略有不同......

关于我认为退出进程会杀死其所有子进程的信念,我进一步调查并发现:Is there any UNIX variant on which a child process dies with its parent?。简而言之:我的信念是错误的。感谢那个迫使我启蒙的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-04
    • 2015-05-14
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 2019-03-07
    相关资源
    最近更新 更多