Please, consider the
fork
program given below:
How many times does the following program print hello?
main(int argc, char **argv) {
int i;
for (i=0; i < 3; i++) {
fork();
printf("hello\n");
}
}
Total “hello” messages = 2 + 4 + 8 = 14 (see question-1 at page-5).
How many times does the following program print hello?
#include <stdio.h>
#include <unistd.h>
main()
{
int i;
for (i=0; i<3; i++)
fork();
printf("hello\n");
}
Total “hello” messages = 8 (see question-4 at page-5).
It seems to me both program are same. Why are explanation/answer is different?
Can you explain, please?
Here printf("hello\n”);
statement in first program is inside the for
loop.
for (i=0; i < 3; i++) {
fork();
printf("hello\n”);
}
And, printf("hello\n”);
statement in second program is outside the for
loop.
for (i=0; i<3; i++)
fork();//after semicolon printf is outside the for loop's block scope.
printf("hello\n");
That is difference between both given code.