您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

C无阻塞键盘输入

C无阻塞键盘输入

如前所述,您可以使用sigactionctrl-c select陷阱或任何标准输入。

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

您需要使用该tcsetattr()功能关闭ICANON模式,并且可能也禁用ECHO。从内存中,您还必须在程序退出时将终端设置回ICANON模式!

为了完整起见,这里有一些我刚刚删除代码(nb:没有错误检查!),它设置了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);
}

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 */
}
其他 2022/1/1 18:20:10 有646人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶