programing

C 논블로킹 키보드 입력

randomtip 2022. 11. 2. 23:25
반응형

C 논블로킹 키보드 입력

사용자가 키를 누를 때까지 루프하는 프로그램을 C(Linux)로 작성하려고 하는데, 각 루프를 계속하기 위해 키를 누를 필요는 없습니다.

간단한 방법이 있을까요?내가 할 수 있을 것 같아select()일이 많은 것 같아요

또는 non-blocking io가 아닌 프로그램 종료 전에 c-키를 눌러 정리하는 방법이 있습니까?

이미 언급했듯이sigactionctrl+c를 트랩하다select모든 표준 입력을 트랩합니다.

다만, 후자의 방식에서는, TTY 가 line-at-a-time 모드가 아닌 character-at-a-time 모드가 되도록 설정할 필요도 있습니다.후자가 기본값입니다. 텍스트를 한 줄 입력하면 Enter 키를 누를 때까지 실행 중인 프로그램의 stdin으로 전송되지 않습니다.

를 사용해야 합니다.tcsetattr()ICANON 모드를 끄고 ECHO도 비활성화합니다.프로그램을 종료할 때 메모리에서 단말기를 ICANON 모드로 다시 설정해야 합니다!

완전성을 위해서, 여기 UNIX TTY 를 셋업 해, DOS 를 에뮬레이트 하는 몇개의 코드가 있습니다(nb: no error check!).<conio.h>기능들kbhit()그리고.getch():

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <termios.h>

struct termios orig_termios;

void reset_terminal_mode()
{
    tcsetattr(0, TCSANOW, &orig_termios);
}

void set_conio_terminal_mode()
{
    struct termios new_termios;

    /* take two copies - one for now, one for later */
    tcgetattr(0, &orig_termios);
    memcpy(&new_termios, &orig_termios, sizeof(new_termios));

    /* register cleanup handler, and set the new terminal mode */
    atexit(reset_terminal_mode);
    cfmakeraw(&new_termios);
    tcsetattr(0, TCSANOW, &new_termios);
}

int kbhit()
{
    struct timeval tv = { 0L, 0L };
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(0, &fds);
    return select(1, &fds, NULL, NULL, &tv) > 0;
}

int getch()
{
    int r;
    unsigned char c;
    if ((r = read(0, &c, sizeof(c))) < 0) {
        return r;
    } else {
        return c;
    }
}

int main(int argc, char *argv[])
{
    set_conio_terminal_mode();

    while (!kbhit()) {
        /* do some work */
    }
    (void)getch(); /* consume the character */
}

차단되지 않는 키보드 입력을 받는 또 다른 방법은 장치 파일을 열고 읽는 것입니다.

찾고 있는 디바이스 파일(/dev/input/event* 중 하나)을 알아야 합니다.cat /proc/bus/input/devices를 실행하여 원하는 디바이스를 찾을 수 있습니다.

이 코드는 관리자 권한으로 실행됩니다.

  #include <stdlib.h>
  #include <stdio.h>
  #include <unistd.h>
  #include <fcntl.h>
  #include <errno.h>
  #include <linux/input.h>

  int main(int argc, char** argv)
  {
      int fd, bytes;
      struct input_event data;

      const char *pDevice = "/dev/input/event2";

      // Open Keyboard
      fd = open(pDevice, O_RDONLY | O_NONBLOCK);
      if(fd == -1)
      {
          printf("ERROR Opening %s\n", pDevice);
          return -1;
      }

      while(1)
      {
          // Read Keyboard Data
          bytes = read(fd, &data, sizeof(data));
          if(bytes > 0)
          {
              printf("Keypress value=%x, type=%x, code=%x\n", data.value, data.type, data.code);
          }
          else
          {
              // Nothing read
              sleep(1);
          }
      }

      return 0;
   }

다음과 같이 select를 사용하여 이를 수행할 수 있습니다.

  int nfds = 0;
  fd_set readfds;
  FD_ZERO(&readfds);
  FD_SET(0, &readfds); /* set the stdin in the set of file descriptors to be selected */
  while(1)
  {
     /* Do what you want */
     int count = select(nfds, &readfds, NULL, NULL, NULL);
     if (count > 0) {
      if (FD_ISSET(0, &readfds)) {
          /* If a character was pressed then we get it and exit */
          getchar();
          break;
      }
     }
  }

너무 많은 작업이 필요 없음:D

select()사용하기에는 조금 낮은 레벨입니다.를 사용하는 것이 좋습니다.ncurses라이브러리를 사용하여 단말기를 cbreak 모드와 delay 모드로 설정하고 콜합니다.getch()이 값은 반환됩니다.ERR준비된 문자가 없는 경우:

WINDOW *w = initscr();
cbreak();
nodelay(w, TRUE);

그 시점에서 전화하실 수 있습니다.getch차단하지 않습니다.

여기 당신을 위해 이것을 하는 기능이 있습니다.당신은 필요하다termios.hPOSIX 시스템과 함께 제공됩니다.

#include <termios.h>
void stdin_set(int cmd)
{
    struct termios t;
    tcgetattr(1,&t);
    switch (cmd) {
    case 1:
            t.c_lflag &= ~ICANON;
            break;
    default:
            t.c_lflag |= ICANON;
            break;
    }
    tcsetattr(1,0,&t);
}

분석:tcgetattr현재 단말기 정보를 가져와 저장합니다.t.한다면cmd는 1 입니다.로컬 입력 플래그t는 비표준 입력으로 설정됩니다.그렇지 않으면 리셋됩니다.그리고나서tcsetattr표준 입력을 로 변경t.

프로그램의 마지막에 표준 입력을 리셋 하지 않으면 셸에 문제가 생깁니다.

UNIX 「」를 사용할 수 .sigaction에 의해, 「」의 시그널 가 등록됩니다.SIGINTControl+C를 사용합니다.신호 핸들러는 플래그를 설정할 수 있으며 플래그는 루프 내에서 체크되어 적절히 끊어집니다.

당신은 아마 원할 것이다.kbhit();

//Example will loop until a key is pressed
#include <conio.h>
#include <iostream>

using namespace std;

int main()
{
    while(1)
    {
        if(kbhit())
        {
            break;
        }
    }
}

일부 환경에서는 동작하지 않을 수 있습니다. 스레드를 스레드에 .getch();

저주 라이브러리를 이 용도로 사용할 수 있습니다. ★★★★★★★★★★★★★★★★★.select()및 신호 핸들러도 어느 정도 사용할 수 있습니다.

Control-C를 잡는 것만으로도 만족한다면, 이미 끝난 거래입니다.정말로 비블로킹 I/O를 원하지만 저주 라이브러리를 원하지 않는 경우, 또 다른 대안은 잠금, 스톡, 배럴을 AT&T 라이브러리로 옮기는 것입니다.C에 무늬가 있는 멋진 도서관입니다.stdiosfio는 안전하고 /O합니다.

이를 위한 휴대용 방법은 없지만 select()를 사용하는 것이 좋습니다.보다 많은 해결 방법에 대해서는, http://c-faq.com/osdep/readavail.html 를 참조해 주세요.

C++에서는, 다음과 같이 했습니다.

#include <chrono>
#include <thread>

using namespace std::chrono_literals;

void OnEnter()
{
    while (true)
    {
        getchar();
        // do something when enter is pressed
    }
}

int main()
{
    std::thread keyBoardCommands(OnEnter);

    while(true)
    {
        // code for main loop
        std::this_thread::sleep_for(16ms);
    }
}

이 코드는 플랫폼에 의존하지 않습니다.

언급URL : https://stackoverflow.com/questions/448944/c-non-blocking-keyboard-input

반응형