Visually what happens to fork() in a For Loop

后端 未结 3 797
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 06:11

I have been trying to understand fork() behavior. This time in a for-loop. Observe the following code:

#include 

void main()
{
         


        
3条回答
  •  不知归路
    2020-12-02 06:30

    1. Yes, it's correct. (see below)
    2. No, i++ is executed after the call of fork, because that's the way the for loop works.
    3. If all goes successfully, yes. However, remember that fork may fail.

    A little explanation on the second one:

    for (i = 0;i < 3; i++)
    {
       fork();
    }
    

    is similar to:

    i = 0;
    while (i < 3)
    {
        fork();
        i++;
    }
    

    So i in the forked processes(both parent and child) is the value before increment. However, the increment is executed immediately after fork(), so in my opinion, the diagram could be treat as correct.

提交回复
热议问题