I want to chain the stdin and stdout of several programs via named pipe. These programs act like services or daemons so I wish they could keep reading from a FIFO until they are blocked due to the FIFO is cleared. I modified the code from the answer in the question C++: Read from stdin as data is written into pipe as below to verify my idea:
#include <iostream>
int main() {
char input;
while(1){
while(std::cin>>input){
std::cout<<input;
}
}
}
Then I compiled this to an executable named t. Now open a terminal and enter these commands:
mkfifo ff
./t > ff
And open a new terminal and enter this:
./t < ff
Now inputs to the first terminal will appear at the second terminal, and the t in the second terminal would be blocked as soon as it has read all characters in the FIFO. Everything is fine by now, but when I terminate the t in the first terminal, the t in the second terminal is not blocked anymore, nevertheless the FIFO is cleared already, and soon takes up 100% CPU usage even when the FIFO is deleted.
My questions:
- Why the second
tis not blocked when the firsttexits in my case; - Is there anyway to keep the second
tbeing blocked when the firsttexits; - Maybe my whole idea about chaining programs via FIFO is wrong. Is there a better practise to connect the stdin and stdout of several programs in shell?