I'm working on a C project that's supposed to be similar to Unix's "more" command. Like "more", this program is supposed to be able to get its input from either a file(if specified) or stdin if no file is given (so the output of other programs can be piped into it) and display it to stdout. Also like "more", echoing and canonical mode are supposed to be disabled, which I've done with the following code:
//change terminal attributes
tcgetattr(0, &info); //Get info
tcgetattr(0, &orig_inf); //Save original info
info.c_lflag &= ~ECHO; //Disable echo
info.c_lflag &= ~ICANON; //Disable canonical mode
info.c_cc[VMIN] = 1; //Get 1 char at a time
tcsetattr(0, TCSANOW, &info); //Set attributes
To read user commands from the keyboard, I'm opening "dev/tty" explicitly rather than just reading from stdin:
//Open cmd stream
if((cmd = fopen("/dev/tty", "r")) == NULL){
perror("Failure opening command stream");
tcsetattr(0, TCSANOW, &orig_inf);
exit(EXIT_FAILURE);
}
and reading them with getc(cmd). This works fine when the user provides a file to read from, but if the program is receiving input from stdin, it seems like the terminal attributes are being reset. I can see every command I try to type (which means echoing is on again) and commands don't get sent to the program unless I hit enter (meaning canonical mode has somehow been reactivated again). I've searched the web and all of the man pages for almost all of the system calls I'm using, and can't seem to find a reason for this.
If anyone knows why this is happening and how to fix it, help would be much appreciated.
Thanks!