Fgets (): Ok on console, Bad 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); } } 

gives:

Console:

 ./a.out input input 

and then expects more input. That is, it repeats stdin for stdout, similar to cat .

On the channel:

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

after launch, it floods the console on its own, without interaction.

This sample program is exactly what I used for the tests; this is not a segment. I would expect the two tests to behave the same. What's happening?

+4
source share
3 answers

Once EOF reached, fgets immediately returns NULL without waiting for input (or a buffer change). Thus, it will rotate endlessly. In the tube body, echo closes the tube as soon as it dials "input\n" , which will result in EOF.

Change fgets call to

 if(fgets(stdinput, 10, stdin) == NULL) break; 
+6
source

You can simply replace the loop condition with your fgets call by specifying:

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

This will loop until you get EOF, in which case fgets() returns NULL in the same way as @nneonneo . But with this condition you do not have to break your while() .

+6
source

[ Note : solves the wrong problem.]

See http://sweslo17.blogspot.tw/2012/04/c-standard-input-redirection.html .

After fgets() you can add below code to restore stdin again to solve pipe problems.

 freopen("/dev/tty","rb",stdin); 
0
source

Source: https://habr.com/ru/post/1435459/


All Articles