我试图用C编写一个程序(在Linux上),循环直到用户按下一个键,但不需要按键来继续每个循环。
有没有简单的方法来做到这一点?我想我可以做到这一点,select()
但似乎很多工作。
或者,有没有办法在程序关闭之前捕获ctrl- c按键来清理而不是非阻塞的io?
发布于 2018-05-03 16:15:16
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <termios.h>
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))) < 0) {
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 */
}
发布于 2018-05-03 17:29:22
WINDOW *w = initscr();
cbreak();
nodelay(w, TRUE);
https://stackoverflow.com/questions/-100008345
复制相似问题