user1134316
user1134316

Reputation:

Why does fork() and printf() output more than I predict?

This is my little program:

#include <unistd.h>
#include <stdio.h>
int main() {
  printf("1");
  fork();
  printf("2");
  fork();
  return 0;
}

The output of this code is 12121212 and I ask:
Why does it print more than 122?

Upvotes: 2

Views: 541

Answers (3)

SzG
SzG

Reputation: 12619

If printf() goes to a terminal, it is line buffered by default. Simply printing "1\n" and "2\n" would solve your problem.

Upvotes: 0

ahmad88me
ahmad88me

Reputation: 1

Another Solution is to use write + sprintf

e.g.

char s[10];
sprintf(s,"four is %d",4);
write(STDOUT_FILENO,s,sizeof(s));

Upvotes: 0

George Nechifor
George Nechifor

Reputation: 439

Because printf is buffered and the text is printed only when program exits. Try to flush stdout after each print.

Upvotes: 6

Related Questions