Advertisement
Guest User

poll-demo.c

a guest
Apr 22nd, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | None | 0 0
  1.  
  2. // <poll.h> demo
  3. //
  4. // in response to: https://boards.4channel.org/g/thread/70651197#p70656634
  5. //
  6. // see: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/poll.h.html
  7. //      http://man7.org/linux/man-pages/man2/poll.2.html (more helpful)
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h> // strchr(), strerror()
  12. #include <errno.h>
  13.  
  14. #include <poll.h>
  15.  
  16. #define BUFFSZ 1024
  17. char buffer[BUFFSZ];
  18.  
  19. #define len(array) (sizeof(array) / sizeof(array[0]))
  20.  
  21. #define HIGHLIGHT "\033[2m"
  22. #define NORMVIDEO "\033[0m"
  23.  
  24. int main() {
  25.     struct pollfd p[1];
  26.     int whatever;
  27.  
  28.     p[0].fd = fileno(stdin);
  29.     p[0].events = (POLLIN | 0);
  30.  
  31.     whatever = 0;
  32.  
  33.     while(1) {
  34.         poll(p, len(p), 3); // 3 milli-second timeout
  35.  
  36.         if(p[0].revents == POLLIN) {
  37.             char *line = fgets(buffer, sizeof(buffer)-1, stdin);
  38.  
  39.             // error handling...
  40.  
  41.             if(!line) {
  42.                 int err = errno;
  43.                 fprintf(stderr, "[err=%d] msg=%s\n", err, strerror(err));
  44.                 exit(1);
  45.             }
  46.  
  47.             // process input...
  48.  
  49.             char *n = strchr(line, '\n');
  50.             if(n) *n = '\0';
  51.  
  52.             printf("You entered: '%s%s%s', cycle == %d\n",
  53.                                  HIGHLIGHT, line, NORMVIDEO, whatever);
  54.         }
  55.         else {
  56.  
  57.             // other non-input activities...
  58.             whatever++;
  59.         }
  60.     }
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement