#include<stdio.h>
#include<termios.h>
#include<fcntl.h>
 
int main()
{
 fd_set rfds,rs;
 struct timeval tv;
   
 int i,r,q,j;
 struct termios saveterm,nt;
 int fd=0;
 unsigned char c,buf[32],str[8];
 
 tcgetattr(fd,&saveterm);
 nt=saveterm;
 
 nt.c_lflag &= ~ECHO;      
 nt.c_lflag &= ~ISIG;      
 nt.c_lflag &= ~ICANON;    
 
 tcsetattr(fd,TCSANOW,&nt);
 
 FD_ZERO(&rs);
 FD_SET(fd,&rs);    
 tv.tv_sec=0;
 tv.tv_usec=0;
 
 i=0; q=0;
 while(1)
 {
    read(fd,buf+i,1);
    sprintf(str,"<X>",*(buf+i));
    i++;
    if(i>31)
    {
       write(1,"Too many data\n",14);
       break;
    }
    write(1,str,4);
    r=select(fd+1,&rfds,NULL,NULL,&tv);    
    if(r<0)
    {
       write(1,"select() error.\n",16);
       break;
    }
    if(r==1)
        continue;    
    write(1,"\t",1);
    rfds=rs;
    for(j=0;j<i;j++)
    {
       c=buf[j];
       switch(c)
       {
           case 27 : write(1,"ESC ",4);
                 break;
               case 9 : write(1,"TAB ",4);
                   break;
           case 32 : write(1,"SPACE ",6);
                 break;
              default: if(c>=32 && c<127) write(1,buf+j,1);
               else write(1,"CTRL ",5);
                break;
        }
    }
    write(1,"\n",1);    
    if(buf[0]==27 && i==1)
    {
           if(q==0)
            q=1;
       else
        break;
    }
    else
       q=0;
    i=0;
 }
 
 tcsetattr(fd,TCSANOW,&saveterm);
 printf("\n");
 return 0;

}


说明:连续按下两次ESC键程序退出。

Logo

更多推荐