简体   繁体   中英

Why the output of this C program that uses fork and shared memory like that?

I have question from old exam, Given a C code and m is global variable, when the program finish what the value of m,the answer is "between 7 and 19" but i don't understand why, can someone explain it to me why the answer is between 7-19 and not exactly 19.

int m = 0;

int main() {
    int i;

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

The first thing to notice, analysing this problem is that there are no blocking calls, this means that when the main process reaches the end of main the program will finish, regardless of what state the other processes are in.

Using this fact we can work out the lower limit of m : this will be when the forked processes don't change the value of m before the main process exits. In this case m will start at 3, and be added to 4 times in the loop, giving you the lower limit of m = 7 .

The upper limit will happen when all processes have been spawned before any enters the loop and then each process will add 4 to m (which will have a starting value of 3). In other words, m = 3 + N*4 where N is the total number of processes spawned.

So to finally get the upper limit we need to know how many processes are spawned. The first call of fork() will turn one process into two, and the subsequent call of fork() will turn each of these processes into two, meaning that N = 4 .

Using our expression for m from before then we see that the upper limit is m = 3 + 4 * 4 = 19

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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