Blame manual/examples/termios.c

Packit 6c4009
/* Noncanonical Mode Example
Packit 6c4009
   Copyright (C) 1991-2018 Free Software Foundation, Inc.
Packit 6c4009
Packit 6c4009
   This program is free software; you can redistribute it and/or
Packit 6c4009
   modify it under the terms of the GNU General Public License
Packit 6c4009
   as published by the Free Software Foundation; either version 2
Packit 6c4009
   of the License, or (at your option) any later version.
Packit 6c4009
Packit 6c4009
   This program is distributed in the hope that it will be useful,
Packit 6c4009
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit 6c4009
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
Packit 6c4009
   GNU General Public License for more details.
Packit 6c4009
Packit 6c4009
   You should have received a copy of the GNU General Public License
Packit 6c4009
   along with this program; if not, if not, see <http://www.gnu.org/licenses/>.
Packit 6c4009
*/
Packit 6c4009
Packit 6c4009
#include <unistd.h>
Packit 6c4009
#include <stdio.h>
Packit 6c4009
#include <stdlib.h>
Packit 6c4009
#include <termios.h>
Packit 6c4009
Packit 6c4009
/* Use this variable to remember original terminal attributes. */
Packit 6c4009
Packit 6c4009
struct termios saved_attributes;
Packit 6c4009
Packit 6c4009
void
Packit 6c4009
reset_input_mode (void)
Packit 6c4009
{
Packit 6c4009
  tcsetattr (STDIN_FILENO, TCSANOW, &saved_attributes);
Packit 6c4009
}
Packit 6c4009
Packit 6c4009
void
Packit 6c4009
set_input_mode (void)
Packit 6c4009
{
Packit 6c4009
  struct termios tattr;
Packit 6c4009
  char *name;
Packit 6c4009
Packit 6c4009
  /* Make sure stdin is a terminal. */
Packit 6c4009
  if (!isatty (STDIN_FILENO))
Packit 6c4009
    {
Packit 6c4009
      fprintf (stderr, "Not a terminal.\n");
Packit 6c4009
      exit (EXIT_FAILURE);
Packit 6c4009
    }
Packit 6c4009
Packit 6c4009
  /* Save the terminal attributes so we can restore them later. */
Packit 6c4009
  tcgetattr (STDIN_FILENO, &saved_attributes);
Packit 6c4009
  atexit (reset_input_mode);
Packit 6c4009
Packit 6c4009
/*@group*/
Packit 6c4009
  /* Set the funny terminal modes. */
Packit 6c4009
  tcgetattr (STDIN_FILENO, &tattr);
Packit 6c4009
  tattr.c_lflag &= ~(ICANON|ECHO); /* Clear ICANON and ECHO.  */
Packit 6c4009
  tattr.c_cc[VMIN] = 1;
Packit 6c4009
  tattr.c_cc[VTIME] = 0;
Packit 6c4009
  tcsetattr (STDIN_FILENO, TCSAFLUSH, &tattr);
Packit 6c4009
}
Packit 6c4009
/*@end group*/
Packit 6c4009
Packit 6c4009
int
Packit 6c4009
main (void)
Packit 6c4009
{
Packit 6c4009
  char c;
Packit 6c4009
Packit 6c4009
  set_input_mode ();
Packit 6c4009
Packit 6c4009
  while (1)
Packit 6c4009
    {
Packit 6c4009
      read (STDIN_FILENO, &c, 1);
Packit 6c4009
      if (c == '\004')		/* @kbd{C-d} */
Packit 6c4009
	break;
Packit 6c4009
      else
Packit 6c4009
	putchar (c);
Packit 6c4009
    }
Packit 6c4009
Packit 6c4009
  return EXIT_SUCCESS;
Packit 6c4009
}