Can anyone explain and trace this because my teacher can't
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 :
开发者_C百科i = 2 , j = 24
i = 2 , j = 24
any brief explain or trace would be great Thanks
p
is uninitialized and never changed.
int j = 10, p; //uninitialized
while (i-- && p == fork()) //comparison - no changes
if ( p < 0 ) exit(1); //comparison - no changes
if (p == 0) { //comparison - no changes
so p
happens to store whatever value is there in the memory plus whatever the compiler assigns uninitialized variables to.
Assuming that was a typo, and while (i-- && p == fork())
was really while (i-- && (p = fork()))
, then the output depends on the OS scheduler.
The main process forks off processes with
- i=1 p=0 <-- process A, parent.p=A
- i=0 p=0 <-- process B, parent.p=B
- i=-1 p=B <-- parent process, parent.p = B
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:
A: i=+1 p=0 j=12
B: i= 0 p=0 j=12
P: i=-1 p=*B* j=12
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:
i = -2, j = 24
i = 3, j = 36
i = 0, j = 36
(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.
精彩评论