Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outcome of a small C program

Tags:

c

fork

unix

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?

like image 562
Ikke Avatar asked Nov 30 '22 20:11

Ikke


2 Answers

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.

like image 57
JaredPar Avatar answered Dec 04 '22 06:12

JaredPar


15 is printed by child, and 3 by parent.

like image 31
qrdl Avatar answered Dec 04 '22 06:12

qrdl