C fork dealing with global variable

前端 未结 5 1182
谎友^
谎友^ 2021-01-05 01:37

I\'m not understanding the output of this program:

#include 
#include 
#include 

int i = 0;

int main()
{
           


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-05 01:52

    It's something like...

     1 (main) instance, i = 0(unforked)
     fork() > 2 instances, with i's = 0(forked), and 0(forked)
    0 output from main instance, increments its i, 2 instances with i = 1u, 0f
     main instance forks, there's 3 instances with i's 1f, 1f, 0f
    1 output from main instance, increments its i, 3 instances with i = 2u, 1f, 0f
     main instance forks, there's 4 instances with i's 2f, 2f, 1f, 0f
    2 output from main instance, increments its i, 4 instances with i = 3u, 2f, 1f, 0f
     main instance then dies, 3 instances with i = 2f, 1f, 0f
    2 output from next instance, increments its i, 3 instances with i = 3u, 1f, 0f
     next instance then dies, 2 instances with i = 1f, 0f
    1 output from next instance, increments its i to 2, 2 instances with i = 2u, 0f
    

    ...etc

    The order that the processes are outputting in, however, is undetermined, so you likely won't see the exact same output every time, and even if you do it's not something you can guarantee.

    As other people said, each process has its own global 'i' that it keeps track of, and its value is simply the value of the forking process's i at the fork.

提交回复
热议问题