繁体   English   中英

在 fork() 之后,我的程序中不断获得相同的 pid

[英]I keep getting the same pid in my program after fork()

这是代码

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。这是否意味着它是相同的进程

如果 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM