프로그래밍/Unix/Linux

블럭킹없이 키입력 받기(non blocking)

AlwaysNR 2015. 7. 2. 12:05

루프내에서 키입력을 체크하거나 받고싶을때...

DOS/Windows 환경의 kbhit()함수같은게 필요할때...

아래 함수 사용하면 될듯...

#include <termios.h>

#include <fcntl.h>

#include <stdio.h>

int kbhit(void)

{

  struct termios oldt, newt;

  int ch;

  int oldf;


  tcgetattr(STDIN_FILENO, &oldt);

  newt = oldt;

  newt.c_lflag &= (~(ICANON | ECHO));

  tcsetattr(STDIN_FILENO, TCSANOW, &newt);

  oldf = fcntl(STDIN_FILENO, F_GETFL, 0);

  fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

 

  ch = getchar();

 

  tcsetattr(STDIN_FILENO, TCSANOW, &oldt);

  fcntl(STDIN_FILENO, F_SETFL, oldf);

 

  if(ch != EOF)

  {

    ungetc(ch, stdin);


    return 1;

  }


  return 0;

}


응용하면 getchar_nonblock()같은것도 만들 수 있고...