Linux while 获取键盘输入退出

  • c 语言实现如下:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <termios.h>
    #include <termio.h>
    #include <unistd.h>
    #include <fcntl.h>
    #include <errno.h>

    int kbhit(void)
    {
        struct timeval tv;
        struct termios old_termios, new_termios;
        int error;
        int count = 0;

        tcgetattr(0, &old_termios);        // 获取之前的标准输入终端状态
        new_termios = old_termios;   

        new_termios.c_lflag &= ~ICANON;    // 设置行模式原始输入
        new_termios.c_lflag &= ~ECHO;       // 设置行模式原始输入
        new_termios.c_cc[VMIN] = 1;
        new_termios.c_cc[VTIME] = 0;
        error = tcsetattr(0, TCSANOW, &new_termios);        // 设置 标准输入终端 状态立即生效
        tv.tv_sec = 0;
        tv.tv_usec = 100;
        select(1, NULL, NULL, NULL, &tv);            // 监控

        error += ioctl(0, FIONREAD, &count);        // 获取标准输入的字符
        error += tcsetattr(0, TCSANOW, &old_termios); // 还原 标准输入终端状态

        return error == 0 ? count : -1;        // 如果有字符输入会返回非零
    }

    int main(void)
    {
        while(!kbhit())               // 返回非零退出
        {
            printf("chenfulin is sb\n");
            sleep(1);
        }
        return 0;
    }
posted @ 2017-09-19 15:23  陈富林  阅读(581)  评论(0编辑  收藏  举报