一步一步学Linux C:底层终端编程实例


Linux 系统的终端处理是一个非常大的系统,需要处理许多不同类型的设备和需求。涉及的内容包括:调制解调器、终端仿真、伪终端等。

Linux 系统处理终端的方法是通过串行接口连接的控制台与系统通信并运行程序。由于越来越多的厂商都参与到终端的生产,而且每个厂商都为自己的终端设计自己的命令集,所以需要有一种方法对终端的访问进行一般化处理。Linux 系统使用一个能力数据库terminfo来描述每个终端的能力以及调用这些功能的方法。

在某些情况下,程序员希望能够对某些并不是终端的设备提供终端驱动程序功能,这时需要用到伪终端。伪终端提供一种方法,让程序员假装成为一个真正的终端,并能够良好地与系统交互。

下面程序的功能是查询和打印当前终端的一些能力

  1. #include <stdlib.h>   
  2. #include <stdio.h>   
  3. #include <term.h>   
  4. #include <curses.h>   
  5. #define NUMCAPS 3   
  6.   
  7. int main()  
  8. {  
  9.     int j;  
  10.     int retval = 0;  
  11.     char * buf;  
  12.     char *boolcaps[NUMCAPS] = {"am","bce","km"};  
  13.     char *numcaps[NUMCAPS] = {"cols","lines","colors"};  
  14.     char *strcaps[NUMCAPS] = {"cup","flash","hpa"};  
  15.   
  16.     if(setupterm(NULL,fileno(stdin),NULL) != OK){  
  17.     perror("setupterm()");  
  18.     exit(EXIT_FAILURE);  
  19.     }  
  20.   
  21.     for(j = 0;j<NUMCAPS;++j){  
  22.     retval = tigetflag(boolcaps[j]);  
  23.     if(retval == FALSE)  
  24.         printf("%s unsuported\n",boolcaps[j]);  
  25.     else  
  26.         printf("%s suported\n",boolcaps[j]);  
  27.   
  28.     }  
  29.   
  30.   
  31.     for(j = 0;j<NUMCAPS;++j){  
  32.     retval = tigetnum(numcaps[j]);  
  33.     if(retval == ERR)  
  34.         printf("%s unspported\n",numcaps[j]);  
  35.     else  
  36.         printf("%s is%d\n",numcaps[j],retval);  
  37.   
  38.     }  
  39.   
  40.   
  41.     for(j = 0;j<NUMCAPS;++j){  
  42.     buf = tigetstr(strcaps[j]);  
  43.     if(buf == NULL)  
  44.         printf("%s unspported\n",strcaps[j]);  
  45.     else  
  46.         printf("%s is%d\n",strcaps[j],buf[0]);  
  47.   
  48.     }  
  49.   
  50. }  

注意:编译此程序时要手动连接libcurses.a,编译方式为gcc  test.c -o test -lcurses

相关内容