linux下,实现按键直接输入(无按enter)

termios的实现中,有大量的参数设置,还有伪终端的说法。原因就在于当初UNIX发明时,(上世纪七十~八十年代),在美国,西欧大学里面用的都是大型机加客户终端,学生们用的是串口方式与大型机进行交流,通讯。所以,当时很多软件的设计都是针对这种情况而开发的。包括termios,tty,X window等等。因为要在串口上传输,所以不得不定义很多按键的组合符号和很多传输模式。

#include
#include

static struct termios initial_settings, new_settings;
static int peek_character = -1;
void init_keyboard(void);
void close_keyboard(void);
int kbhit(void);
int readch(void);

void init_keyboard()
{
    tcgetattr(0,&initial_settings);
    new_settings = initial_settings;
    new_settings.c_iflag |= IGNCR;

    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;
}

int main()
{
    init_keyboard();
    int key_num;
    while(1)
    {
        kbhit();
        key_num = readch();
        if(key_num == 3)
            break;
        printf("%d\n", key_num);
        system("echo hello");
    }
    close_keyboard();
    return 0;
}

你可能感兴趣的:(linux下,实现按键直接输入(无按enter))