简体   繁体   English

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

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

This is the code这是代码

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);
    }
}

The loop is supposed to create two different processes but whenever I run this the output pid is always 0. Does this mean it the same process该循环应该创建两个不同的进程,但是每当我运行它时,输出 pid 始终为 0。这是否意味着它是相同的进程

if pid == 0 your code is executing the child process.如果 pid == 0 您的代码正在执行子进程。 If pid is different than 0 your code execute the parent process如果 pid 不同于 0 您的代码执行父进程

see section return value of the man http://man7.org/linux/man-pages/man2/fork.2.html参见 man http://man7.org/linux/man-pages/man2/fork.2.html 的部分返回值

you can find out the real pid of the child with function getpid你可以用函数getpid找出孩子的真实pid

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

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

相关问题 如何使用fork和execv获取程序的pid - How to get the pid of a program started with fork and execv 我不断从cin.get()中获取程序空间 - I keep getting a space in my program from cin.get() 为什么我的程序始终无法获取外部信息? - Why do I keep getting unresolved externals for my program? 原始输入后,我一直得到零 - I keep getting zeros when after my original inputs 我无法让我的程序工作我不断收到未定义的符号:c - i cant get my program to work i keep getting undefined symbol: c 子项和父项pid与fork(); - Child and Parent pid with fork(); 在fork()之后,如何在for()循环中继续运行execve()? - After fork(), how to keep running execve() in for() loop? 即使“用户”输入数字||,我在运行程序时仍会得到0。 C ++绘画工作 - I keep getting 0's when I run my program even though the “user” inputs numbers || c++ painting job 我正在为我祖母的生日编写 C++ 程序,但是我不断收到错误代码:错误 C2451 - I am working on a C++ program for my grandmother's birthday, however I keep getting error code: error C2451 我是编程新手。 编译包含 ah 文件中包含的 class 定义的代码后,我不断收到错误消息 - I am new in programming. I keep getting an error message after compiling my code that contains a class definition included in a .h file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM