0
votes

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 t is not blocked when the first t exits in my case;
  • Is there anyway to keep the second t being blocked when the first t exits;
  • 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?
1

1 Answers

0
votes

Why the second t is not blocked when the first t exits in my case

When the first t is terminated, it generates an end of file on the fifo and the second t is not blocked anymore.

Is there anyway to keep the second t being blocked when the first t exits

This is a problem in inter process communication (IPC). The input/output to the IPC mechanism (fifo, here) should be done inside the C++ program.

Is there a better practise to connect the stdin and stdout of several programs in shell?

If the processes are related you can connect by the pipe (|) operator. Otherwise, using a fifo with redirection appears to be the only way.