2

A question was aked about how many A's are to be printed after running the following code in C:

int i;
for (i=1;i<4;i++){
     fork();
     printf("A");
}

I counted 14 on my own. However, after running it the asnwer turned out to be 24. Later I ran an altered version:

 int i;
 for (i=1;i<4;i++){
      fork();
       printf("A\n");
 }

Which printed 14 A's. I'd love someone to explain this to me.

Alex
  • 85
  • 1
  • 8
  • Since you do not verify the return value of `fork()`, I will assume that you will have hit your maximum number of processes. – marcolz Jun 29 '16 at 16:01

2 Answers2

6

The reason for the different number of A's is line buffering.

The first version does not print a new-line, so the printf is not actually written out until the program exits.

Since the fork() call duplicates the entire running process it also duplicates the buffered line of A's.

Then as each process exits it flushes its buffers to output.

The second version of the program flushes its output with every printf call because of the new-line and the fact that most C implementations flush the buffers on new-line, if you are printing to a terminal. (It doesn't flush if you're printing to a file or network socket.)

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
  • So to make your program more predicatable, call `fflush(stdout);` right after each call to `printf`. That way, nothing is left in the standard output buffer of your process when you go to fork. Then you should get 14 As every time. – David Grayson Jun 29 '16 at 16:17
0

This happens due to the fact that printf is line-buffered , i.e., its buffer gets flushed only upon encountering a new-line.

In the second case, you have put a '\n' , and thus the expected behavior happens as each time the buffer is getting cleared.

In the first case,

After first fork() :

  Buffer : A

After second fork() :

  Buffer : AA

After third fork() :

  Buffer : AAA ( 3 A's exist in the buffer )

Thus, finally as you have 8 processes totally, 8 * 3 = 24. Therefore 24 A's

Apoorva K H
  • 111
  • 5