I encountered a question to say the result printed out of the program.
#include <unistd.h>
#include <stdio.h>
void func() {
for (int i = 0; i < 2; ++i) {
fork();
printf("-");
}
}
int main() {
func();
return 0;
}
And I expected the result to be "------" (six '-'). Because
- Parent process forks, each of them prints a '-'. (2 processes)
- The two processes forks, and they all prints out '-'. (4 processes)
- Now value of i is 2, loop is over.
So the program should prints 6 characters.
But when I actually run the program, I get 8 characters. What's more strange is that when I run it again it prints 2 characters. Seems the result is random among 2, 4, 6 or 8.
Why the result is uncertain? Is there something related to undefined behaviors? Even if I turned off optimization (-O0), it's still like this.