TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: Neil Heller
from: Jasen Betts
date: 2003-05-29 22:11:40
subject: Keyboard questions

Hi Neil.


ypu asked about asynchronous keyboard (IE not waitong for keys)
and raw mode (no line editing, or echo)

here's a little demo prog I cooked up with lots of help from the on-line
documentation.


/---* (BAZ.C)
#include 
#include 
#include 
#include 
#include 
#include 

     /* Use this variable to remember original terminal attributes. */

struct termios
 saved_attributes;

void reset_input_mode(void)
{
  tcsetattr(STDIN_FILENO, TCSANOW, &saved_attributes);
}

void set_input_mode(void)
{
  struct termios tattr;
  char *name;

  /* Make sure stdin is a terminal. */
  if (!isatty(STDIN_FILENO)) {

 fprintf(stderr, "Not a terminal.\n");
    exit(EXIT_FAILURE);
  }

  /* Save the terminal attributes so we can restore them later. */
  tcgetattr(STDIN_FILENO, &saved_attributes);

  atexit(reset_input_mode);

  /* Set the funny terminal modes. */

 tcgetattr(STDIN_FILENO, &tattr);
  tattr.c_lflag &= ~(ICANON | ECHO);        /* Clear ICANON and ECHO. */
  tattr.c_cc[VMIN] = 1;
  tattr.c_cc[VTIME] = 0;

  tcsetattr(STDIN_FILENO, TCSAFLUSH, &tattr);
}


int main(void)
{
  char c;
  int n=0, res;

  fd_set rfds;
  struct timeval tv;
  int retval;

  tv.tv_usec = 1;

  set_input_mode();
  while(1) {

    FD_ZERO(&rfds);
    FD_SET(STDIN_FILENO, &rfds);
    /* Wait up to five seconds. */

    tv.tv_sec = 0;
    if (tv.tv_usec == 0)   // has timer run out?
      tv.tv_usec = 200000;

    retval = select(1, &rfds, NULL, NULL, &tv);
       // select waits for timer or input

    if (retval) {
      !read(STDIN_FILENO, &c, 1)
      if (c == '\004')  /* Ctrl-d to exit */
        break;
      else {
        putchar(c);
      }
    } else
      n = (n + 1)
 & 3;
    putchar("/-\\|"[n]);  // a simple "twirler"
    putchar('\010');
    fflush(stdout);       // gotta gave this if no newline is emitted
  }

  return EXIT_SUCCESS;
};


 -=> Bye <=-

---
* Origin: Black Holes were created when God divided by zero! (3:640/1042)
SEEN-BY: 633/267 270
@PATH: 640/1042 531 954 774/605 123/500 106/2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.