1. 程式人生 > >linux下,實現按鍵直接輸入(無按enter)

linux下,實現按鍵直接輸入(無按enter)

termios的實現中,有大量的引數設定,還有偽終端的說法。原因就在於當初UNIX發明時,(上世紀七十~八十年代),在美國,西歐大學裡面用的都是大型機加客戶終端,學生們用的是串列埠方式與大型機進行交流,通訊。所以,當時很多軟體的設計都是針對這種情況而開發的。包括termios,tty,X window等等。因為要在串列埠上傳輸,所以不得不定義很多按鍵的組合符號和很多傳輸模式。

#include <stdio.h>
#include <termios.h>

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