In: Computer Science
int main(){
int i = 3;
if(fork()){
i++;
fork();
i+=3;
}else{
i+=4;
fork();
i+=5;
}
printf("%d\n",i);
}
what is the output of the code
OUTPUT:
7 7 12 12
NOTE: The order of the numbers in output changes randomly after every execution, because the compiler is executing all the processes in the same execution space.
EXPLANATION:
When the function starts there's 1 process, this process has a int i= 3.
Now, when fork() executes, we have two processes. They both have the same execution space, they both are going to run the same code (to a point), but the child will get its own copy of i.
Now, when fork() will return a 0 to the child process. the rest of the function according to child's prospective is:
else{
i+=4;
fork();
i+=5;
}
printf("%d\n",i);
Now the value of i is updated to 7.
Again the fork() function spilts the child process into two further subprocesses.Both processes recieves the updated value of i(i.e 7). Now both the process runs seperately in the same execution space. After i+=5 statement, both the processes prints the value( i.e 12 12)
The parent process on the other hand, will get a valid value back from the fork() command, thus it executes the line of if statement.
if(fork()){
i++;
fork();
i+=3;
}
printf("%d\n",i);
Now the value of i is updated to 4.
Again the fork() function spilts the child process into two further subprocesses.Both processes recieves the updated value of i(i.e 4). Now both the process runs seperately in the same execution space. After i+=3 statement, both the processes prints the value( i.e 7 7)