the question in the exam was :
write the output of the following program :
int i = 2 ;
int main () {
int j = 10, p ;
while (i-- && p == fork())
if ( p < 0 ) exit(1);
j += 2;
if (p == 0) {
i *= 3;
j *= 3;
}
else {
i *= 2;
j *= 2;
}
printf("i = %d, j = %d \n",i,j);
return 0;
}
Output from the console using xcode with include this lines before int i = 2; :
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
Output:
i = 3, j = 36
i = 0, j = 36
i = -3, j = 36
Note: I notice that the output is different if we use the Ubuntu.
i think this is the output of the Ubuntu :
i = 2 , j = 24
i = 2 , j = 24
any brief explain or trace would be great Thanks
Assuming that was a typo, and
while (i-- && p == fork())was reallywhile (i-- && (p = fork())), then the output depends on the OS scheduler.The main process forks off processes with
Processes A and B do not continue the loop, because the
p=fork()evaluates as false for them.Each process adds 2 to j (which might as well be j=12). In summary:
The cases where p=0, have i and j multiplied by 3, the ones with p!=0 (the parent process) have them multiplied by 2. This yields the following perfectly reasonable output for me:
(The order is going to be somewhat random)
As sharptooth pointed out, your code as written is simply producing random results, depending on a piece of uninitialized memory.