본문 바로가기

About 배우고 익히는법/펌글

[Linux] linux에서 getch() 및 kbhit() 사용하기

Linux에서는 함수 getch() 및 함수 kbhit()가 존재하긴 한다.

헤더파일도 conio.h로 주어지고 있고...

 

문제는 일반 컴파일러가 아니라

보드용 컴파일러, 즉 PC 환경이 아니라 임베디드 환경에서 작업할 때는

위의 헤더인 conio.h가 거의 주어지지 않는다.

 

따라서 getch() 및 kbhit() 를 사용하기 위해서는

직접 만들어 써야 한다는 어려움이 있다.

 

그래서 여기에 이와 동일한 작업을 하는 함수를 만들어 본다.

 

 

1. linux_kbhit.h 헤더 파일

 

#ifndef LINUX_KBHIT_H_
#define LINUX_KBHIT_H_

 

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

 

int linux_kbhit(void)
{
    struct termios oldt, newt;
    int ch;

 

    tcgetattr( STDIN_FILENO, &oldt );
    newt = oldt;

 

    newt.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newt );

 

    ch = getchar();

 

    tcsetattr( STDIN_FILENO, TCSANOW, &oldt );

 

    return ch;
}

 

#endif

 

2. linux_kbhit() 함수를 이용한 간단한 main 예제

 

#include <stdio.h>
#include <iostream>
#include "linux_kbhit.h"

 

int main(void)
{
    int previous_keystroke = 0;
   
    printf("\n");
    printf("Type any key to see the return ASCII int of the key pressed.\n");
    printf("The program will start in 1sec. Press <Esc> to quit...\n\n");
    sleep(1);
   
    while(1)
    {
        int value = linux_kbhit();
       
        // key stroke detected
        if (value != -1)
        {
            // printing of key integer value
            printf("%d\n", value);
        }

 

        // detection of <Esc> key.    # of integer value set:    1
        //                            integer value:            27
        if ((previous_keystroke == 27) && (value == -1))
            break;
        previous_keystroke = value;
       
        // printing of '.'s to prove non-blocking of kbhit()
        printf(".");
    }
   
    printf("\n");
    printf("<Esc> key pressed. Bye bye\n\n");
   
    return 0;
}