The result of a small C program

We need to report the result of the following C program:

main() { int pid, k, som; som = 0; k = 2; pid = fork(); if(pid == 0) k=5; else wait(0); for(int i = 1; i <= k; i++) som += i; printf("%d", som); } 

My first expectation is 3. When the fork call is made, the process memory is copied and both programs start. Then the child process is executed, but k is still equal to 2. Thus, in the end it executes 1 + 2 = 3;

But when this program is executed, it outputs 153. I do not have the closest key why it outputs it.

Can someone say why?

+4
source share
4 answers

The reason you have 2 printing processes on the same console. "fork" is a unix / linux command that is called once and returned twice. One of the returns will be in the original process called fork, and will return the PID of the child process that was spawned. The second return will be 0, and this means that this is a child process.

One of the programs that I think runs first and calculates 15 as a value and prints it to the last console. The parent program executes the second because of the wait (0) and returns a value of 3.

+15
source

15 is printed by the child, and 3 by the parent.

+4
source

A is the parent, B is the child, here are the important lines:

 A: pid = fork(); // returns 0 for the child process A: wait(0); B: k = 5; B: for(int i = 1; i <= k; i++) som += i; // som = 15 B: printf("%d", som); // prints 15, B finishes, goes back to A A: for(int i = 1; i <= k; i++) som += i; // som = 3 A: printf("%d", som); // prints 3 
+2
source

A new line is not printed between the values, so the parent answer appears immediately after the child answers.

Jared correctly explained the reason for the meanings.

0
source

Source: https://habr.com/ru/post/1286435/


All Articles