C ++:在数据写入管道时从标准输入读取

C++: Read from stdin as data is written into pipe

我有两个 C++ 程序:一个将消息打印到标准输出,另一个侦听标准输入并打印流中的所有内容。它们分别命名为outin

out.cpp:

#include <iostream>

using namespace std;

int main() {
        cout<<"HELLO";
        usleep(1000000);
        cout<<"HELLO";
}

in.cpp:

#include <iostream>

using namespace std;

int main() {
        string input;
        while(cin>>input) {
                cout<<input;
        }
}

按照目前的情况,将数据从 out 传输到 in 等待两秒钟,然后打印 HELLOHELLO:

~$ ./out | ./in

#...two seconds later:
~$ ./out | ./in
HELLOHELLO~$

我确定这是一个简单的问题,但是 in 是否可以像 out 一样打印每个 HELLO?我读过 piped commands run concurrently,但对于这种特殊情况,我一定是误解了这个概念。期望的性能是:

~$ ./out | ./in

#...one second later:
~$ ./out | ./in
HELLO

#...one second after that:
~$ ./out | ./in
HELLOHELLO~$

这里有两个问题。

首先是输出缓冲。你需要flush the output stream。 可能最简单的方法是 cout.flush().

第二种是字符串读全字,你只输出一个,中间有停顿。

您要么需要切换到基于字符的输入,要么在单词之间放置一个分隔符。

基于字符的输入看起来像这样

int main() {
        char input;
        while(cin>>input) {
                cout<<input;
        }
}

添加分隔符如下所示:

int main() {
        cout<<"HELLO";
        cout<<" ";
        usleep(1000000);
        cout<<"HELLO";
}

注意额外的 space。