2
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<errno.h>
int main()
{
   printf("abcd");
   fork ();
   printf("pqrs\n");
   return 0;
}

This program gives the output as follows:

abcdpqrs
abcdpqrs

But how is it possible? Shouldn't it be:

abcdpqrs
pqrs
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
nupadhyaya
  • 1,909
  • 1
  • 14
  • 14

2 Answers2

4

No

it's because fork also copies the datastructure used in printf, holding the buffer to be printed out.

If you fork the program, the buffer is not flushed.

El Hocko
  • 2,581
  • 1
  • 13
  • 22
3

printf does not necessarily flush stdout immediately, so what happens is that "abcd" is buffered until next output is executed. Since later both "sides" of the fork do the output, both will also flush out the "abcd".

To make it work the way you're probably guessing it would, try flushing manually;

int main()
{

   printf("abcd");
   fflush(stdout);
   fork ();
   printf("pqrs\n");
   return 0;
}

$ ./a.out 
abcdpqrs
pqrs
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294