⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tty_raw.c

📁 Linux Kernel Programming by Examples(1)[Xeroo]
💻 C
字号:
/* @file tty_raw.c * * R. Stevens Adv. Prog. in UNIX Env. p.355 * */#include <stdio.h>   // printf#include <stdlib.h>  // exit#include <signal.h>#include <termios.h>#include <unistd.h>static struct termios termios_save;static int    ttysavefd = -1;static enum { RESET, RAW, CBREAK } ttystate = RESET;int tty_reset( int fd );static voidsig_catch( int signo ){  printf("signal caught. No %d\n", signo );  tty_reset( STDIN_FILENO );  exit(0);}inttty_raw( int fd ){  struct termios buf;  if ( tcgetattr( fd, &termios_save ) < 0 )     return -1;  buf = termios_save; // struct copy  buf.c_lflag &= ~( ECHO | ICANON | IEXTEN | ISIG );  buf.c_iflag &= ~( BRKINT | ICRNL | INPCK | ISTRIP | IXON );  buf.c_cflag &= ~( CSIZE | PARENB );  buf.c_cflag |= CS8;  buf.c_oflag &= ~( OPOST );  buf.c_cc[VMIN] = 1;  buf.c_cc[VTIME] = 0;  if ( tcsetattr( fd, TCSAFLUSH, &buf ) < 0 )    return -1;  ttysavefd = fd;  ttystate  = RAW;  return 0;} inttty_reset( int fd ){  if ( ttystate != RAW )    return 0;  if ( tcsetattr( fd, TCSAFLUSH, &termios_save) < 0 )    return -1;  ttystate = RESET;  return 0;}voidtty_atexit( void ){  if ( ttysavefd >= 0 )    tty_reset( ttysavefd );}struct termios *tty_termios( void ){  return &termios_save;}intmain( int argc, char ** argv ){  int  i;  char c;    if ( signal( SIGINT, sig_catch ) == SIG_ERR ) {    printf("signal(SIGINT) error\n");    exit(1);  }  if ( signal( SIGTERM, sig_catch ) == SIG_ERR ) {    printf("signal(SIGTERM) error\n");    exit(1);  }  if ( signal( SIGQUIT, sig_catch ) == SIG_ERR ) {    printf("signal(SIGQUIT) error\n");    exit(1);  }  if ( tty_raw( STDIN_FILENO ) < 0 ) {    printf("tty_raw(STDIN) error\n");    exit(2);  }  printf("Enter raw mode characters. Terminate with DELETE\n");  while ( (i = read(STDIN_FILENO, &c, 1)) == 1) {    if ( (c &= 255) == 0177 ) {      break;    }    printf("%o\n", c );  }  if ( tty_reset( STDIN_FILENO ) < 0 ) {    printf("tty_reset(STDIN) error\n");  }  if ( i <= 0 ) {    printf("read error %d\n", i );  }  exit(0);}    

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -