0

I am just experimenting with fork() c++ function.but I found Surprising results

#include<stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <signal.h>
int main()
{
 int x=0;
  int i;
  for( i=0;i<2;i++)
  {
    fork();
    x=x+5;
    printf("%d\n",x);
   sleep(2);
  }
  return 0;
}

This code is giving output as expected 5

5

10

10

10

10

but same code behaves very differently when I replaced new line in printf with space

int main()
{
 int x=0;
  int i;
  for( i=0;i<2;i++)
  {
    fork();
    x=x+5;
    printf("%d  ",x);
   sleep(2);
  }
  return 0;
}

5 10 5 10 5 10 5 10

Can anyone tell why so abnormal result came when I replaced new line with space.

I am using gcc compiler gcc version 4.1.2 20080704 (Red Hat 4.1.2-48)

Thanks a lot in advance

2 Answers2

4

The standard output stream is normally line-buffered. When you include the \n when printing, you flush the stream and the 5 is printed to the console before the next fork() is called. When you don't include it, it's just hanging around in a buffer someplace and gets duplicated along with everything else when fork is called.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
3

printf is only guaranteed to flush the buffer when you do a \n If you don't do one, then other things can be written to a buffer and then flushed later, with the elements in different orders (depending one when it was added to the buffer).

soandos
  • 4,978
  • 13
  • 62
  • 96