Zeokav Zeokav - 3 months ago 9
C Question

Why does my output differ for this code snippet?

I have recently started a course on Operating Systems. I came across this question where I need to figure out what the output is. Here is the code -

int main() {
int val = 5;
if(fork()) {
wait(&val);
}
val++;
printf("%d ", val);
return val;
}


This has been answered on SO before on this post - Explain this code's working; how the child process returns values and where?

I understand how the return value is returned to val from the child process, which is then incremented and printed in the parent process, and the output according to that logic should in fact be 6 7


But when I tried executing the code myself, I seem to be getting something completely different. I get an output 6 1537. If I remove the increment, I get the output - 6 1280

What this implies is that the value being returned is val*256 and not just val(which is not in accordance with that answer I linked). I have tried looking on the internet for an explanation but I can't seem to find an answer. Would really help if anyone can explain what's happening here.

Answer

The wait() system call puts more than just the return value from the child process in the returned value from wait(). In fact just the lower 8 bits are the returned value, the higher bits are status flags, indicating among other things how the child exited (by a signal for example). To get the return value from the child use:

val = WEXITSTATUS(val);

immediately after the wait().