技巧:“禁用”Linux终端输出的回显


Termios结构是在POSIX规范中定义的一个标准接口,通过设置termios类型的数据结构中值及相关函数调用便可以对终端接口进行控制。

  控制终端的输出回显主要用到"本地模式"中可用的c_lflag的宏ECHO,ECHO宏定义为:启用输入字符的本地回显功能

  此功能最常见的应用莫过于控制输入密码的回显,如通过sudo /etc/**获取管理权限或终端登录MySQL时输入的密码是不会显示出来的。

  而termios结构的定义包含在termios.h头文件中,直接看代码:

  

#include
#include
#include

#define PASSWORD_LEN 12

int main(){
struct termios initialrsettings, newrsettings;
char password[PASSWORD_LEN + 1];
tcgetattr(fileno(stdin),&initialrsettings); #获取termios结构并保存
newrsettings = initialrsettings;
newrsettings.c_lflag &= ~ECHO; #清除变量c_lflag中由ECHO定义的比特
printf("Please Enter Password:");
if( tcsetattr(fileno(stdin),TCSAFLUSH,&newrsettings) != 0 ){
fprintf(stderr,"Could not set arrributes\n");
}else{
fgets(password,PASSWORD_LEN,stdin);
tcsetattr(fileno(stdin),TCSANOW,&initialrsettings); #还原之前的termios结构
fprintf(stdout,"\nYou entered %s as the password\n",password);
}
exit(0);
}


  最后编译、运行之,达到预期目的~

  不同Linux发行版需要包含的头文件可能存在细微的差异,以下是我主机的信息:

   Hardware:i686
OS:Linux (ubuntu desktop 7.10)
Release:2.6.22-14-generic
Version:#1 SMP Tue Feb 12 07:42:25 UTC 2008

 

本文作者:
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3