[英]Monitoring data in named pipe (FIFO) in C++
I want to chain the stdin and stdout of several programs via named pipe.我想通过名为 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.这些程序的作用类似于服务或守护程序,因此我希望它们可以继续从 FIFO 读取,直到它们由于 FIFO 被清除而被阻塞。 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:我修改了问题C++: Read from stdin as data is written into pipe中的答案中的代码,如下所示以验证我的想法:
#include <iostream>
int main() {
char input;
while(1){
while(std::cin>>input){
std::cout<<input;
}
}
}
Then I compiled this to an executable named t
.然后我将它编译成一个名为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.现在第一个终端的输入将出现在第二个终端上,第二个终端中的t
将在读取 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.现在一切都很好,但是当我终止第一个终端中的t
时,第二个终端中的t
不再被阻塞,但是 FIFO 已经被清除,并且即使删除 FIFO 也很快会占用 100% 的 CPU 使用率。
My questions:我的问题:
t
is not blocked when the first t
exits in my case;为什么在我的情况下,当第一个t
退出时,第二个t
没有被阻塞;t
being blocked when the first t
exits;当第一个t
退出时,是否有办法阻止第二个t
?Why the second t is not blocked when the first t exits in my case为什么在我的情况下第一个 t 退出时第二个 t 没有被阻止
When the first t
is terminated, it generates an end of file on the fifo and the second t
is not blocked anymore.当第一个t
终止时,它会在 fifo 上生成一个文件结尾,并且第二个t
不再被阻塞。
Is there anyway to keep the second t being blocked when the first t exits当第一个 t 退出时,无论如何要阻止第二个 t
This is a problem in inter process communication (IPC).这是进程间通信(IPC)中的一个问题。 The input/output to the IPC mechanism (fifo, here) should be done inside the C++ program. IPC 机制(此处为 fifo)的输入/输出应在 C++ 程序内完成。
Is there a better practise to connect the stdin and stdout of several programs in shell?连接shell中几个程序的stdin和stdout有没有更好的做法?
If the processes are related you can connect by the pipe (|) operator.如果进程相关,您可以通过 pipe (|) 运算符进行连接。 Otherwise, using a fifo with redirection appears to be the only way.否则,使用带有重定向的 fifo 似乎是唯一的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.