Advertisement
jpenguin

getch.c

Feb 24th, 2020
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <termios.h>
  5. #include <unistd.h>
  6.  
  7. #include "getch.h"
  8.  
  9. static struct termios _term;
  10.  
  11. int
  12. getch (void) {
  13. int c = EOF;
  14. int i = 0;
  15. int len = sizeof(signals) / sizeof(signals[0]);
  16. struct termios term, ttmp;
  17.  
  18. // get stdin attributes
  19. tcgetattr(STDIN_FILENO, &term);
  20.  
  21. // get stdin attributes and store in static `_term variable for
  22. // a global copy
  23. tcgetattr(STDIN_FILENO, &_term);
  24.  
  25. // store state of stdin
  26. ttmp = term;
  27.  
  28. // canonical input and echo modes
  29. ttmp.c_lflag &= ~(ICANON|ECHO);
  30.  
  31. // set stdin attributes on tmp termio struct now with `TCSANOW`
  32. tcsetattr(STDIN_FILENO, TCSANOW, &ttmp);
  33.  
  34. // bind signal handles
  35. for (; i < len; ++i) {
  36. signal(signals[i], on_signal);
  37. signal(signals[i], on_signal);
  38. signal(signals[i], on_signal);
  39. signal(signals[i], on_signal);
  40. signal(signals[i], on_signal);
  41. signal(signals[i], on_signal);
  42. }
  43.  
  44. // get char from modified stdin
  45. c = getchar();
  46.  
  47. // reset stdin to previous state
  48. tcsetattr(STDIN_FILENO, TCSANOW, &term);
  49.  
  50. return c;
  51. }
  52.  
  53. static void
  54. on_signal (int signal) {
  55. tcsetattr(STDIN_FILENO, TCSANOW, &_term);
  56. exit(1);
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement