Why is the main call twice?

I just found out about fork, and as I understand it, a child process starts execution from a fork call (would fork be recursive otherwise?).

However, in this code ( ideone link ):

int main() {
  printf("%d: Common code1\n", getpid());
  if (fork() != 0) {
    printf("%d: Parent code\n", getpid());
  } else {
    printf("%d: Child code\n", getpid());
  }
  printf("%d: Common code\n", getpid());
}

Conclusion:

27380: Common code1
27380: Parent code
27380: Common code
27380: Common code1
27383: Child code
27383: Common code

I do not understand why the 4th line is printed? I could understand if it was printed from a child process and the main fork, but it was printed from the parent, and fork does not name main.

+4
source share
3 answers

Good question! At first I was a little embarrassed.

printf, . , , printf, , , , , stdout .

. stdout PID . , , . .

, fflush(stdout); fork().

+8

- . stdout , . , , , . , 27380, , 27383, . 27380: Common code1 , , . fflush() , .

+3

Buffering. Printf (usually) writes nothing to stdout. It just updates some internal data structures. These data structures are duplicated in the child, and when the stream is flushed, data is written. You must flush(stdout)before using fork.

+2
source

All Articles