2

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?

Nick
  • 1,334
  • 10
  • 14
  • 2
    possible duplicate of [fork() branches more than expected?](http://stackoverflow.com/questions/11132868/fork-branches-more-than-expected) – Joseph Mark Jun 10 '14 at 09:04
  • 1
    @sjeohp This issue is due to line buffering, not more forks than expected. The questioners expected output suggests that he understands the nature of the forks. – Nick Jun 10 '14 at 09:05
  • Possible duplicate of [printf anomaly after "fork()"](http://stackoverflow.com/questions/2530663/printf-anomaly-after-fork) – Zan Lynx Mar 03 '17 at 01:01

3 Answers3

6

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

George Nechifor
  • 439
  • 3
  • 12
  • Or `setbuf(stdout, NULL)`. – Fred Foo Jun 10 '14 at 09:00
  • 1
    @GeoAoe printf is *LINE* buffered. Doing "1\n" and "2\n" will work fine. – Nick Jun 10 '14 at 09:02
  • Thanks, and why it's wait for program exit? usually `printf()` prints immediately what it get. –  Jun 10 '14 at 09:12
  • @Nick and how the buffer of printf is same from father to child? –  Jun 10 '14 at 09:28
  • @zardav fork() creates a duplicate of the calling process with some shared resources such as code segments and file descriptors, but their own memory segments for data. fork() returns twice, once in the child and once in the parent. Each process will output "12" when they exit, and the two forks will result in 4 processes (2 * 2) from the main process being duplicated, and each of those two forking with the second fork. – Nick Jun 10 '14 at 15:05
  • 1
    @zardav So just to be clear, your program ends 4 times :) (but I think you knew that) – Nick Jun 10 '14 at 15:12
  • Thanks! cleaver, for the other answers, I don't look for solution, I just wanted to know the problem. –  Jun 10 '14 at 15:18
0

Another Solution is to use write + sprintf

e.g.

char s[10];
sprintf(s,"four is %d",4);
write(STDOUT_FILENO,s,sizeof(s));
ahmad88me
  • 3
  • 1
0

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

SzG
  • 12,333
  • 4
  • 28
  • 41