简体   繁体   English

需要帮助来了解fork C ++

[英]Need help understanding fork C++

I am trying to create a program that uses fork to create 4 processes, which I am understanding to be 2 parents and 2 children. 我正在尝试创建一个使用fork创建4个进程的程序,据我了解,这是2个父母和2个孩子。

The way I have set up my code is: 我设置代码的方式是:

for(int i = 0; i < 2; ++i){
     pid_t pid1 = fork();
     switch(pid1){
        case -1:
            fatal("fork failed");
            break;
        case 0:
            child(i);
            break;
        default:
           parent(i);
           break;
     }
}

In child() and parent() respectively, I am calling getpid(). 我分别在child()和parent()中调用了getpid()。 Inside child(), I exit(0) once I am done. 在child()内部,完成后退出(0)。 Inside parent() I wait for the child using wait(0) When I run the program, it outputs 2 different children pids and 2 same parent pids. 在parent()内部,我使用wait(0)等待子项。运行程序时,它将输出2个不同的子pid和2个相同的父pid。 Is this happening because I am calling the same fork() twice? 这是因为我两次调用同一个fork()吗?

  1. Process 1 calls fork for 1st loop iteration, creating process 1.1. 进程1调用fork进行第一次循环迭代,从而创建进程1.1。

  2. Then process 1 calls fork again for 2nd loop iteration, creating process 1.2. 然后,进程1再次调用fork进行第二次循环迭代,从而创建进程1.2。

  3. Then process 1.1 (which is essentially process 1 duplicated when fork was done) also enters 2nd loop iteration, creating process 1.1.1. 然后,过程1.1(实质上是完成fork时重复的过程1)也进入第二循环迭代,创建过程1.1.1。

So processes 1.1 and 1.2 have same parent, process 1. And there are total 4 processes (1, 1.1, 1.2, 1.1.1). 因此,流程1.1和1.2具有相同的父流程,即流程1。并且共有4个流程(1、1.1、1.2、1.1.1)。

Note that steps 2 and 3 may happen in different order, depending on how OS decides to schedule processes. 请注意,步骤2和3可能以不同的顺序发生,具体取决于OS如何决定调度进程。

Because you have used exit function in child(i) function, child will exit and hence only parent process will continue it's execution in for loop. 因为您在child(i)函数中使用了退出函数,所以child将退出,因此只有父进程会继续在for循环中执行它。 So you only get 2 new process forked which are childs of same parent . 因此,您仅会获得2个新进程,它们是同一父进程的子进程。 So parent id stays same but since two childs are created, so get 2 distinct child pids! 因此,父代ID保持不变,但由于创建了两个孩子,因此获得2个不同的孩子pids! If you want four process to be forked, then you will have to erase the exit statement from child(i) function and use if else statements after each fork() call. 如果要分叉四个进程,则必须从child(i)函数中删除exit语句,并在每次fork()调用后使用if else语句。

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

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