如前所述,您可以使用sigaction捕捉ctrl-c,或select捕捉任何标准输入。
但是,请注意,对于后一种方法,您还需要设置TTY,使其处于实时字符模式,而不是逐时模式。后者是默认的-如果键入一行文本,它不会被发送到正在运行的程序的stdin,直到您按Enter键。
您需要使用tcsetattr()函数关闭ICANON模式,也可能也禁用回波。从内存中,您还必须将终端设置回ICANON模式,当程序退出!
为了完整起见,下面是我刚刚编写的一些代码(nb:没有错误检查!),它设置一个UnixTTY并模拟DOS功能kbhit()和getch():#include #include #include #include #include struct termios orig_termios;void reset_terminal_mode(){
tcsetattr(0, TCSANOW, &orig_termios);}void set_conio_terminal_mode(){
struct termios new_termios;
/* take two copies - one for now, one for later */
tcgetattr(0, &orig_termios);
memcpy(&new_termios, &orig_termios, sizeof(new_termios));
/* register cleanup handler, and set the new terminal mode */
atexit(reset_terminal_mode);
cfmakeraw(&new_termios);
tcsetattr(0, TCSANOW, &new_termios);}int kbhit(){
struct timeval tv = { 0L, 0L };
fd_set fds;
FD_ZERO(&fds);
FD_SET(0, &fds);
return select(1, &fds, NULL, NULL, &tv);}int getch(){
int r;
unsigned char c;
if ((r = read(0, &c, sizeof(c)))
return r;
} else {
return c;
}}int main(int argc, char *argv[]){
set_conio_terminal_mode();
while (!kbhit()) {
/* do some work */
}
(void)getch(); /* consume the character */}