为了解释我提出的问题,让我们考虑一下这段代码,
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t child, parent;
parent = getpid();
printf("Main parent pid: %dn",parent );
if((child = fork()) < 0) {
printf("Errorn");
} else if(child == 0 ) {
printf("A Child process is created, pid: %d, ppid: %d n",
getpid(), getppid());
} else if(child > 0) {
printf("Parent says: Child pid: %d, getpid: %d, getppid: %dn",
child, getpid(), getppid());
}
return 0;
}
当我在终端上执行此代码时,我得到这样的输出
Main pid: 711
Parent says: Child pid: 712, getpid: 711, getppid: 598
A Child process is created, pid: 712, ppid: 1
据我了解,当我通过从已经创建的进程分叉来创建新进程时,这个新进程的父进程必须是我分叉的进程。Hovewer,从输出中可以看出,子进程的父进程 ID 是 1,即 init 进程,为什么会这样呢?是我的理解是错误的,还是还有其他一些我没有看到的东西?
注意:我正在使用Mac OSX。
问题是父进程 (711) 在报告之前已经死亡,子进程由 init 进程 (1) 继承。 如果你让父母等孩子死后再退出,你会看到你期望的结果。
要演示:
#include <sys/wait.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
pid_t child, parent;
parent = getpid();
printf("Main parent pid: %dn", (int)parent);
if ((child = fork()) < 0)
{
printf("Errorn");
}
else if (child == 0)
{
printf("A Child process is created, pid: %d, ppid: %dn",
(int)getpid(), (int)getppid());
}
else if (child > 0)
{
printf("Parent says: Child pid: %d, getpid: %d, getppid: %dn",
(int)child, (int)getpid(), (int)getppid());
#ifndef DO_NOT_WAIT_FOR_CHILD
int status;
int corpse = wait(&status);
printf("Child %d exited with status 0x%.4Xn", corpse, status);
#endif
}
return 0;
}
在没有-DDO_NOT_WAIT_FOR_CHILD
的情况下编译时,我得到了示例输出:
Main parent pid: 77646
Parent says: Child pid: 77647, getpid: 77646, getppid: 46383
A Child process is created, pid: 77647, ppid: 77646
Child 77647 exited with status 0x0000
当用-DDO_NOT_WAIT_FOR_CHILD
编译时,我得到了示例输出:
Main parent pid: 77662
Parent says: Child pid: 77663, getpid: 77662, getppid: 46383
A Child process is created, pid: 77663, ppid: 1