【发布时间】: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。