Skip to content
Advertisement

pipe command make standard input broken

I have two processes: t1.cpp and t2.cpp.

t1.cpp and t2.cpp are simplified ,I want to describe the problem easily.

//t1.cpp
#include <iostream>
using namespace std;
int main()
{
    cout << "hellon"
         << "worldn"
         << "ok okn";
    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;
} 

After compiling t1.cpp and t2.cpp. I execute them in this way ./t1 | ./t2.

Problems occur! cin >> x; in t2.cpp failed! I have no chance to type from the keyboard.

It seems the pipe command implements by redirecting the STDIN_FILENO. Does it forbid the standard input simultaneously?

My harsh requirements is obtain data from the output of t1 with shell command |,in addition,I want interact with users in t2.For example,I would display Sure to del?[y/n],and wait users's anwser.

Advertisement

Answer

Finally,we deal this problem using “/dev/tty”

FILE *file = fopen("/dev/tty","r");
if(NULL == file){
    /*error*/
}
int ch = fgetc(file);
if('y' == ch || 'Y' == ch){
    /*balabala*/
}

when stdin or stdout was redirected , we also can read or write from the /dev/tty.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement