tags:

views:

283

answers:

4

We need to tell the outcome 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 a the fork call is made, the memory of the process is copied, and both programs go running. The child process then executes, but k still equals 2. So at the end, it executes 1 + 2 = 3;

But when this program is executed, it outputs 153. I haven't got the nearest clue why it outputs that.

Can anyone tell why?

+15  A: 

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

One of the programs, the child i believe, executes first and calculates 15 as the value and prints it to the console last. The parent program executes second because of the wait(0) and produces the value 3.

JaredPar
offcourse. Totaly forgot that both processes produce output.
Ikke
I believe you are correct. You can quickly discern if this is so by changing the last line of the program to: printf("%d\n", som);
LBushkin
+4  A: 

15 is printed by child, and 3 by parent.

qrdl
A: 

There's no newline being printed between the values so the parent's answer appears right after the child's answer.

Jared's correct about the cause of the values.

Arnshea
+2  A: 

A is 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
CookieOfFortune