我有两个进程:t1.cpp
和t2.cpp
。
t1.cpp
并且t2.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.cpp
和t2.cpp
。我以这种方式执行它们./t1 | ./t2
。
出现问题!cin >> x;
在t2.cpp
失败!我没有机会从键盘打字。
似乎管道命令由redirecting the STDIN_FILENO
. 是否同时禁止标准输入?
我的苛刻要求是从t1
with shell 命令的输出中获取数据|
,另外,我想与用户交互t2
。例如,我会显示Sure to del?[y/n],and wait users's anwser.
最后,我们使用“/dev/tty”处理这个问题
FILE *file = fopen("/dev/tty","r");
if(NULL == file){
/*error*/
}
int ch = fgetc(file);
if('y' == ch || 'Y' == ch){
/*balabala*/
}
当stdin
或stdout
被重定向时,我们也可以从/dev/tty
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句