C: stdout hanging linux pipe

I wrote a simple I / O ping program in C to test the problem with a larger real program. Here linux FD redirection does not work.

Echo Program (aka a.out ):

 #include <stdio.h> int main(int argc, char **argv) { char buff[10]; while (1) { if (fgets(buff, 10, stdin) == NULL) break; printf("PRINT: %s \n", buff); } } 


From Bash, I run it as:

 $ mkfifo IN OUT $ # this is a method to keep the pipes IN and OUT opened over time $ while :; do read; echo Read: $REPLY >&2; sleep 1; done <OUT >IN & $ a.out >OUT <IN & $ echo xyz >IN 

and there is no way out: the Bash while cannot read from OUT .


Let's compare this a.out with cat , which works as expected:

 $ mkfifo IN OUT $ while :; do read; echo Read: $REPLY >&2; sleep 1; done <OUT >IN & $ cat >OUT <IN & $ echo xyz >IN Read: xyz 

This last line is printed to the console in stderr. The cat output, other than a.out, is able to navigate OUT and reach the Bash while , which then outputs it to the console.
What happened to a.out?

+4
source share
1 answer

try adding fflush(stdout) after printf(...) .

+6
source

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


All Articles