首页 > 解决方案 > 在 fork() 之后,我的程序中不断得到相同的 pid

问题描述

这是代码

pid_t pid;
srand(time(NULL));
for (int i=0; i < 2; i++)
{
    pid = fork();
    if (pid < 0)
    {
        std::cout<< "fork failed";
        return -1;
    }

    else if (pid == 0)
    {
        std::cout<< "Process "<< i+1 << " ID: " << pid <<std::endl;
        std::thread one (threadFunction, 0);
        std::thread two (threadFunction, 1);
        std::thread three (threadFunction, 2);
        one.join();
        two.join();
        three.join();
    }
    else
    {
        wait (NULL);
        exit(0);
    }
}

该循环应该创建两个不同的进程,但每当我运行它时,输出 pid 始终为 0。这是否意味着它是同一个进程

标签: c++multithreadingprocess

解决方案


如果 pid == 0 您的代码正在执行子进程。如果 pid 不同于 0,您的代码将执行父进程

请参阅 man http://man7.org/linux/man-pages/man2/fork.2.html的部分返回值

您可以使用函数 getpid 找出孩子的真实 pid

http://man7.org/linux/man-pages/man2/getpid.2.html


推荐阅读