I’ve written a simple I/O echoing program in C to test a problem with a bigger real program. Here, linux FD redirection doesn’t work.
The echoing program (aka a.out) is:
#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 output produced: the Bash while loop isn’t able to read from OUT.
Let’s compare this a.out with cat, which instead 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 on console to stderr.
cat‘s output, differently from a.out’s, is able to travel across OUT and reach the Bash while loop, which then prints it on console.
What’s wrong with a.out?
try to add
fflush(stdout)afterprintf(...).