linux非阻塞键盘输入

来源:互联网 发布:网络语坠吼什么意思 编辑:程序博客网 时间:2024/04/30 15:44

linux常用输入函数scanf和getchar通常都是阻塞式的,如果用户没有输入,程序就一直停在那儿;输入内容后,还需要用户点回车;同时,用户输入的信息,会在屏幕上显示出来。
而某些时候,我们不期望这种阻塞发生,也不想要敲入的按键在屏幕上回显,我们希望这一切都由自己写的程序来控制,键盘被按下,我们能够立刻响应,而不需要额外输入回车。
代码如下:

#include<stdio.h>#include <stdlib.h>#define TTY_PATH            "/dev/tty"#define STTY_US             "stty raw -echo -F "#define STTY_DEF            "stty -raw echo -F "static int get_char();static int get_char(){    fd_set rfds;    struct timeval tv;    int ch = 0;    FD_ZERO(&rfds);    FD_SET(0, &rfds);    tv.tv_sec = 0;    tv.tv_usec = 10; //设置等待超时时间    //检测键盘是否有输入    if (select(1, &rfds, NULL, NULL, &tv) > 0)    {        ch = getchar();     }    return ch;}int main(){    int ch = 0;    system(STTY_US TTY_PATH);    while(1)    {        ch = get_char();        if (ch)        {            printf("key = %d(%c)\n\r", ch, ch);            switch (ch)            {                case 3//ctrl+c                    {system(STTY_DEF TTY_PATH);return 0;}                case '0':                    printf("0\n\r");break;                case '1':                    printf("1\n\r");break;                case '2':                    printf("2\n\r");break;                case '3':                    printf("3\n\r");break;            }        }               }}

运行结果:
这里写图片描述

0 0
原创粉丝点击