gpt4 book ai didi

C非阻塞键盘输入

转载 作者:行者123 更新时间:2023-11-30 17:09:29 26 4
gpt4 key购买 nike

我正在尝试用 C(在 Linux 上)编写一个程序,该程序循环直到用户按下某个键,但不需要按键来继续每个循环。

有没有简单的方法可以做到这一点?我想我可以用 select() 来做到这一点,但这似乎需要很多工作。

或者,有没有办法在程序关闭之前捕获 ctrl-c 按键来进行清理,而不是非阻塞 io?

最佳答案

如前所述,您可以使用 sigaction捕获 ctrl-c,或 select捕获任何标准输入。

但请注意,使用后一种方法时,您还需要设置 TTY,使其处于一次字符模式而不是一次一行模式。后者是默认设置 - 如果您输入一行文本,则在按 Enter 之前它不会发送到正在运行的程序的标准输入。

您需要使用tcsetattr()函数可以关闭 ICANON 模式,也可能禁用 ECHO。根据内存,当程序退出时,您还必须将终端设置回 ICANON 模式!

为了完整起见,这里有一些我刚刚敲出的代码(注意:没有错误检查!),它设置了 Unix TTY 并模拟 DOS <conio.h>功能kbhit()getch() :

#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) > 0;
}

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 */
}

关于C非阻塞键盘输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33271966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com