Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgets(): Ok by console, Bad by pipe

Tags:

c

linux

io

pipe

Executing the following C code

#include <stdio.h>
int main(int argc, char **argv) {
  char stdinput[10];
  while (1) {
    fgets(stdinput, 10, stdin);
    fputs(stdinput, stdout);
  }
}

produces:

By console:

./a.out
input
input

and then it waits for more input. That is, it echoes stdin to stdout, similarly to cat.

By pipe:

echo input | ./a.out
input
input
input
[...]

after being started, it floods the console, all by itself, without interaction.

This example program is exactly what I used for the tests; it's not a cut. I would expect the two tests to behave the same way. What's happening?

like image 755
davide Avatar asked Dec 12 '22 22:12

davide


1 Answers

Once EOF is reached, fgets returns NULL immediately without waiting for input (or modifying the buffer). Thus, it will loop infinitely. In your pipe case, echo will close the pipe once it has written "input\n", resulting in EOF.

Change your fgets call to

if(fgets(stdinput, 10, stdin) == NULL)
    break;
like image 103
nneonneo Avatar answered Dec 24 '22 08:12

nneonneo