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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With