I have a piece of C code that uses the fork() system call and I’m confused about its output. Here’s the code:
int main() {
int i;
for (i = 0; i < 1; i++) {
printf("%d", i);
if (fork() == 0) {
printf("%d", i+1);
}
}
printf("7");
}
When I run this code, the output is 07017. I am puzzled about where the second 0 comes from. I assumed that once the fork() is called, the child process would not execute the printf(“%d”, i) statement again as it should start execution from the point after the fork(). Can someone explain why the child process prints the 0 again, contributing to the unexpected output?
I expected it to be 0717.
catcherOfPitcher is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.