gpt4 book ai didi

linux - 管道命令使标准输入中断

转载 作者:太空宇宙 更新时间:2023-11-04 12:21:43 25 4
gpt4 key购买 nike

我有两个进程:t1.cppt2.cpp

t1.cppt2.cpp 是简化的,我想简单的描述问题。

//t1.cpp
#include <iostream>
using namespace std;
int main()
{
cout << "hello\n"
<< "world\n"
<< "ok ok\n";
return 0;
}

//t2.cpp
#include <iostream>
#include <limits>
using namespace std;
int main()
{
string str;
while(getline(cin,str)){
cout << str <<endl;
}

//cin.clear();
//flush the cin
//cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');

char x;
cin >> x;
return 0;
}

编译t1.cppt2.cpp后。我以这种方式执行它们 ./t1 | ./t2.

出现问题! cin >> x; t2.cpp 失败!我没有机会从键盘上打字。

管道命令似乎是通过重定向 STDIN_FILENO 实现的。是否同时禁止标准输入?

我的苛刻要求是使用 shell 命令 |t1 的输出中获取数据,此外,我想与 t2 中的用户进行交互.例如,我会显示Sure to del?[y/n],并等待用户的回答。

最佳答案

实际上,您可以在 C++ 代码中做一些事情。 t1 必须从标准输入读取并将其回显到重定向的标准输出。你可以在不同的地方做这样的事情:

T value;
std::cin >> value;
std::cout << value;

或者在注释中模拟 shell 命令的行为(在 t1 完成将其数据写入 stdout 之后附加 stdin):

std::copy(std::istreambuf_iterator<char>(std::cin),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(std::cout));

关于linux - 管道命令使标准输入中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45737358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com