rotate.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* rotate.c : map a->b, b->c, .. z->a
  2. * purpose: useful for showing tty modes
  3. */
  4. #include <stdio.h>
  5. #include <termios.h>
  6. #include <fcntl.h>
  7. #include <string.h>
  8. #include <signal.h>
  9. int main()
  10. {
  11. int c;
  12. signal( SIGINT, SIG_IGN );
  13. signal( SIGTSTP, SIG_IGN );
  14. signal( SIGQUIT, SIG_IGN );
  15. tty_mode(0); /* save current mode */
  16. set_cr_noecho_mode(); /* set -icanon, -echo */
  17. while ( ( c=getchar() ) != EOF ){
  18. if ( c == 'Q') {
  19. tty_mode(1);
  20. exit(0);
  21. }
  22. else if ( c == 'z' )
  23. c = 'a';
  24. else if (islower(c))
  25. c++;
  26. putchar(c);
  27. }
  28. }
  29. set_cr_noecho_mode()
  30. /*
  31. * purpose: put file descriptor 0 into chr-by-chr mode and noecho mode
  32. * method: use bits in termios
  33. */
  34. {
  35. struct termios ttystate;
  36. tcgetattr( 0, &ttystate); /* read curr. setting */
  37. ttystate.c_lflag &= ~ICANON; /* no buffering */
  38. ttystate.c_lflag &= ~ECHO; /* no echo either */
  39. ttystate.c_cc[VMIN] = 1; /* get 1 char at a time */
  40. tcsetattr( 0 , TCSANOW, &ttystate); /* install settings */
  41. }
  42. set_nodelay_mode()
  43. /*
  44. * purpose: put file descriptor 0 into no-delay mode
  45. * method: use fcntl to set bits
  46. * notes: tcsetattr() will do something similar, but it is complicated
  47. */
  48. {
  49. int termflags;
  50. termflags = fcntl(0, F_GETFL); /* read curr. settings */
  51. termflags |= O_NDELAY; /* flip on nodelay bit */
  52. fcntl(0, F_SETFL, termflags); /* and install 'em */
  53. }
  54. /* how == 0 => save current mode, how == 1 => restore mode */
  55. /* this version handles termios and fcntl flags */
  56. tty_mode(int how)
  57. {
  58. static struct termios original_mode;
  59. static int original_flags;
  60. if ( how == 0 ){
  61. tcgetattr(0, &original_mode);
  62. original_flags = fcntl(0, F_GETFL);
  63. }
  64. else {
  65. tcsetattr(0, TCSANOW, &original_mode);
  66. fcntl( 0, F_SETFL, original_flags);
  67. }
  68. }