Makes sense, so what cat hello.txt | CommandArg is doing is the following;
1) | creates a pipe
2) sets stdin of CommandArg to stdout of cat
3) runs the programs
So now I'm faced with yet another snag, so the atty() function tests if stdin is a keyboard(I think?), if so, then the following block gets the redirected information.
but the problem is IF I run the program with redirection then stdin is now permanently set to the output of a program such as cat. Let's say I ask the user to enter an age regardless of if the program is running from a terminal or not, the age will not be gotten from the keyboard but still from the pipe. So how do I change or maybe restore stdin of my program back to the keyboard?
Side question: why is the function isatty() named so? tty is short hand for terminal these days, why are we checking if it's a terminal, shouldn't we be checking if it's a keyboard? so maybe isakeyboard()?
Even if we use piping such as cat hello.txt | ./CommandArg
We are still running this command in the terminal (tty) ??????
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <unistd.h>
#include <stdio.h>
using namespace std;
int main(int argc,char* argv[])
{
// redirection read
if(!isatty(fileno(stdin))){
string p;
while(cin >> p)
cout << p << endl;
for(int i = 1; i < argc; ++i)
cout << argv[i] << endl;
}else{
cout << "enter your name" << endl;
string p;
getline(cin,p);
cout << p << endl;
}
cout << "enter age" << endl;
int age;
cin >> age;
}
| |