reasons why pipe buffering not working correctly

55 Views Asked by At

I countered something that really irritate me while running this code on https://cpp.sh/

// taken from here https://cplusplus.com/reference/cstdlib/atoi/
#include <stdio.h>      /* printf, fgets */
#include <stdlib.h>     /* atoi */

int main ()
{
  //* setbuf(stdout, NULL);
  int i;
  char buffer[256];
  printf ("Enter a number: ");
  fgets (buffer, 256, stdin);
  i = atoi (buffer);
  printf ("The value entered is %d. Its double is %d.\n",i,i*2);
  return 0;
}

it shows the next output (entered "10\n" as input):

10 
Enter a number: The value entered is 10. Its double is 20.

I am familiar with the concept of linux pipes and buffering, and I know that the pip flush the content of stdout before listening to input, so I wonderd why fgets don't flush stdout before waiting to input.

when removing the comment from the line with * it works as expected, and while compile and run with gcc (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0 also works, so I don't understand whats going on when I run it on the online c++ compiler?

1

There are 1 best solutions below

5
On BEST ANSWER

By default, stdout is fully buffered unless it's connected to a terminal; in that case it's line-buffered. The prompt won't be printed until the output buffer fills up, which is likely to be 4K bytes.

You can call fflush(stdout) to force the buffer to be written to the pipe.

  printf ("Enter a number: ");
  fflush(stdout);
  fgets (buffer, sizeof buffer, stdin);