UNIX-LINUX编程实践教程->第五章->实例代码注解->setecho.c

一 问题

  设置回显位的状态,命令行参数为y则开启,否则关闭。

二 分析

  标准输入的文件描述符为0.
  使用tcgetattr()函数和termios结构体可获得标准输入的属性。
  使用tcsetattr()函数和termios结构体可以将更改后的属性设置重新写回标准输入。

三 实现

#include <stdio.h>
#include <termios.h>

#define oops(s,x) {perror(s);exit(x)};

main(int ac,char *av[])
{
    struct termios info;
    /*必须带有参数*/
    if(ac == 1)
    {
        exit(0);
    }
    /*读取设备属性*/
    if(tcgetattr(0,&info) == -1)
    {
        oops("tcgettattr",1);
    }
    /*命令行第一个参数的第一个字母为y,则开启回显,否则关闭*/
    if(av[1][0] == 'y')
    {
        info.c_lflag |= ECHO;
    }
    else
    {
        info.c_lflag &= ~ECHO;
    }
    /*将修改后的参数写回设备*/
    if(tcsetattr(0,TCSANOW,&info) == 1)
    {
        oops("tcsetattr",2);
    }
}

四 相关函数及结构体

1 tcgetattr() 函数
读取tty驱动程序的属性
头文件:#include <termios.h>  #include <unistd.h>
函数原型: int tcgetattr(int fd,struct termios *info)
参数:  fd    与终端相关联的文件描述符
       info   指向终端结构的指针
返回值: -1    遇到错误
     0     成功返回

2 tcsetattr()函数
设置tty驱动程序的属性
头文件:#include <termios.h>  #include <unistd.h>
函数原型:int tcsetattr(int fd,int when,struct termios *info);
参数:  fd    与终端相关联的文件描述符
     when  改变设置的时间(TCSANOW 立即;
                   TCSADRAIN 等待驱动程序队列中所有输出都被传送到终端
                   TCSAFLUSH 等待驱动队列中所有输出都备传送出去,然后释放所有队列中的输入数据)
     info   指向终端结构的指针
返回值: -1    遇到错误
     0     成功返回

3 termios结构体
struct termios
{
  tcflag_t c_iflag;  /*input mode flags*/
  tcflag_t c_oflag;  /*output mode flags*/
  tcflag_t c_cflag;  /*control mode flags*/
  tcflag_t c_lflag;  /*local mode flags*/
  cc_t c_c[NCCS];  /*control characters*/
  speed_t c_ispeed;  /*input speed*/
  speed_t c_ospeed;  /*output speed*/
}

posted @ 2013-03-06 09:45  布兰姥爷  阅读(771)  评论(0编辑  收藏  举报