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?
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.
15
is printed by child, and 3
by parent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With