termios.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* Noncanonical Mode Example
  2. Copyright (C) 1991-2019 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU General Public License
  5. as published by the Free Software Foundation; either version 2
  6. of the License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include <unistd.h>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <termios.h>
  18. /* Use this variable to remember original terminal attributes. */
  19. struct termios saved_attributes;
  20. void
  21. reset_input_mode (void)
  22. {
  23. tcsetattr (STDIN_FILENO, TCSANOW, &saved_attributes);
  24. }
  25. void
  26. set_input_mode (void)
  27. {
  28. struct termios tattr;
  29. char *name;
  30. /* Make sure stdin is a terminal. */
  31. if (!isatty (STDIN_FILENO))
  32. {
  33. fprintf (stderr, "Not a terminal.\n");
  34. exit (EXIT_FAILURE);
  35. }
  36. /* Save the terminal attributes so we can restore them later. */
  37. tcgetattr (STDIN_FILENO, &saved_attributes);
  38. atexit (reset_input_mode);
  39. /*@group*/
  40. /* Set the funny terminal modes. */
  41. tcgetattr (STDIN_FILENO, &tattr);
  42. tattr.c_lflag &= ~(ICANON|ECHO); /* Clear ICANON and ECHO. */
  43. tattr.c_cc[VMIN] = 1;
  44. tattr.c_cc[VTIME] = 0;
  45. tcsetattr (STDIN_FILENO, TCSAFLUSH, &tattr);
  46. }
  47. /*@end group*/
  48. int
  49. main (void)
  50. {
  51. char c;
  52. set_input_mode ();
  53. while (1)
  54. {
  55. read (STDIN_FILENO, &c, 1);
  56. if (c == '\004') /* @kbd{C-d} */
  57. break;
  58. else
  59. putchar (c);
  60. }
  61. return EXIT_SUCCESS;
  62. }