C non-blocking keyboard input

前端 未结 10 914
说谎
说谎 2020-11-22 05:59

I\'m trying to write a program in C (on Linux) that loops until the user presses a key, but shouldn\'t require a keypress to continue each loop.

Is there a simple wa

10条回答
  •  逝去的感伤
    2020-11-22 06:42

    You can do that using select as follow:

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

    Not too much work :D

提交回复
热议问题