0

Here is my C program :

int main() {
    fork();
    printf("one ");
    fork();
    printf("two ");
}

The output is :

one two one two one two one two

However, If I change the code and add a \n to the print statement :

int main() {
    fork();
    printf("one\n");
    fork();
    printf("two\n");
}

The output is :

one
one
two
two
two
two

Or sometimes (the order can change) :

one
two
one
two
two
two

Why is the output 8 words in the first program and 6 in the second?

nalzok
  • 14,965
  • 21
  • 72
  • 139
Elison Niven
  • 236
  • 3
  • 12

1 Answers1

1

2 processes execute the first printf(), and then 4 processes execute the second printf(), so there should be 6 output.

In the first code, it seems fork() is executed before what is in the buffer is flushed, then the contents of buffer is duplicated and then excess output appeared.

In the second code, it seems \n had it flush the buffer and therefore no excess output appeared.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70