c++ - fork创建子进程时,parent ID与parent ID不一样

标签 c++ c linux process fork

<分区>

为了解释我要问的问题,让我们考虑这段代码,

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

int main() {    
    pid_t child, parent;
    parent = getpid();
    printf("Main parent pid: %d\n",parent );

    if((child = fork()) < 0) {
        printf("Error\n");
    } 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: %d\n", 
               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

据我所知,当我通过从一个已经创建的进程中 fork 来创建一个新进程时,这个新进程的父进程必须是我 fork 的进程。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: %d\n", (int)parent);

    if ((child = fork()) < 0)
    {
        printf("Error\n");
    }
    else if (child  == 0)
    {
        printf("A Child process is created, pid: %d, ppid: %d\n",
               (int)getpid(), (int)getppid());
    }
    else if (child > 0)
    {
        printf("Parent says: Child pid: %d, getpid: %d, getppid: %d\n",
               (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%.4X\n", 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

关于c++ - fork创建子进程时,parent ID与parent ID不一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41658406/

相关文章:

c++ - 在宏中加入前 n-1 个参数

对指针的内存交换感到困惑

linux - Vim:将所有注释移至文件顶部

c++ - 为什么 for_each 不能在这里选择正确的打印

python - 有没有办法从 C++ 调用 `async` python 方法?

c - 从文件读取整数的有效方法

c - 为什么我在通过内核模块访问 GPIO2 和 GPIO3 时在 Beaglebone Black 上出现段错误?

javascript - 在后台运行React开发服务器的方法

c - 就套接字 API 而言,主动关闭与被动关闭?

c++ - 文本编辑器 API。用于实验性 IDE 的 Scintilla。你用别的东西吗?