how to get keyboard key with non blocking in terminal

/**************************************************************************
 *        how to get keyboard key with non blocking in terminal
 * 声明:
 *      如何在终端下以非堵塞的方式获取按键的键值,这个想法最初是因为
 *  在单线程下实现多任务,同时不因键盘输入而堵塞,核心内容来自网络,
 *  但已经忘了出处。
 * 
 *                                    2015-7-5 晴 深圳 南山平山村 曾剑锋
 *************************************************************************/

                    \\\-*- 目录 -*-/////
                    |  一、cat kbhit.h
                    |  二、cat kbhit.c
                    \\\\\\///////////

一、cat kbhit.h
    #ifndef __KBHIT_H__
        #define __KBHIT_H__
    
        #include <stdio.h>
        #include <termios.h>
        /**
         * 初始化键盘操作
         */
        void init_keyboard(void);
        /**
         * 关闭键盘操作
         */
        void close_keyboard(void);
        /**
         * 判断是否有按键按下,如果有案件按下返回1,没有按键按下
         * 则返回0
         */
        int kbhit(void);
        /**
         * 用于在有案件按下之后,读取字符
         */
        int readch(void);
    
    #endif // __KBHIT_H__

二、cat kbhit.c
    #include "kbhit.h"
    
    static struct termios initial_settings, new_settings;
    static int peek_character = -1;
    
    void init_keyboard()
    {
        tcgetattr(0,&initial_settings);
        new_settings = initial_settings;
        new_settings.c_lflag &= ~ICANON;
        new_settings.c_lflag &= ~ECHO;
        new_settings.c_lflag &= ISIG;
        new_settings.c_cc[VMIN] = 1;
        new_settings.c_cc[VTIME] = 0;
        tcsetattr(0, TCSANOW, &new_settings);
    }
    
    void close_keyboard()
    {
        tcsetattr(0, TCSANOW, &initial_settings);
    }
    
    int kbhit()
    {
        unsigned char ch;
        int nread;
    
        if (peek_character != -1) return 1;
        new_settings.c_cc[VMIN]=0;
        tcsetattr(0, TCSANOW, &new_settings);
        nread = read(0,&ch,1);
        new_settings.c_cc[VMIN]=1;
        tcsetattr(0, TCSANOW, &new_settings);
        if(nread == 1)
        {
            peek_character = ch;
            return 1;
        }
        return 0;
    }
    
    int readch()
    {
        char ch;
    
        if(peek_character != -1)
        {
            ch = peek_character;
            peek_character = -1;
            return ch;
        }
        read(0,&ch,1);
        return ch;
    }
原文地址:https://www.cnblogs.com/zengjfgit/p/4622196.html