歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux基礎知識 >> 技巧:“禁用”Linux終端輸出的回顯

技巧:“禁用”Linux終端輸出的回顯

日期:2017/3/2 14:47:38   编辑: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 © Linux教程網 All Rights Reserved