问题
I want to use libev to listen for keyboard (keystrokes) events in the terminal. My idea is to use (n)curses getch() and set notimeout() (to be nonblocking) to tell getch() not to wait for next keypress.
Is there a file descriptor that getch uses I can watch?
回答1:
If you use initscr()
, the file descriptor you ask for is fileno(stdin)
, since the initscr subroutine is equivalent to:
newterm(getenv("TERM"), stdout, stdin); return stdscr;
If you use newterm(type, outfile, infile)
, the file descriptor is fileno(infile)
.
回答2:
Curses, and all the terminal functions are actually communicating with the actual terminal through the normal standard input and output file descriptors.
What it does is changing flags using special ioctl
calls or sending special control codes directly that are parsed by the terminal program.
This means that the getch
function just reads its input from the standard input, which if you want a file descriptor is STDIN_FILENO
(from the <unistd.h>
header file).
回答3:
This is a getch like function. I'm on Windows now so can't retest it. If you want
it to just listen and not display the chars change like this : newt.c_lflag &= ~(ICANON);
int getch(void)
{
struct termios oldt, newt;
int ch;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON|ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
}
来源:https://stackoverflow.com/questions/16734387/file-descriptor-of-getch