規范模式很簡單:發一個讀請求,輸入完一行后,終端驅動程序即刻返回。下列幾個條件都會造成讀返回:
?
實例:getpass函數
Getpass函數:讀入用戶在終端上鍵入的口令。此函數由UNIX login(1)和crypt(1)程序調用。為了讀口令(密碼),該函數必須禁止回顯,但仍可使終端以規范模式進行工作,因為用戶在鍵入口令后,一定要鍵入回車,這樣也就構成了一個完整行。
?
程序清單18-8 getpass函數的典型UNIX實現
#include <signal.h>
#include <stdio.h>
#include <termios.h>
?
#define MAX_PASS_LEN????8????/* max #chars for user to enter */
?
char *
getpass(const char *PRompt)
{
????static char????buf[MAX_PASS_LEN + 1];????/* null byte at end */
????char????????*ptr;
????sigset_t????sig, osig;
????struct termios????ts, ots;
????FILE????????*fp;
????int????????c;
????
????if((fp = fopen(ctermid(NULL), "r+")) == NULL)
????????return(NULL);
????setbuf(fp, NULL);
????
????sigemptyset(&sig);
????sigaddset(&sig, SIGINT);????/* block SIGINT */
????sigaddset(&sig, SIGTSTP);????/* block SIGTSTP */
????sigprocmask(SIG_BLOCK, &sig, &osig);????/* and save mask */
????
????tcgetattr(fileno(fp), &ts);????/* save tty state */
????ots = ts;????????????/* sturcture copy */
????ts.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);????/* 禁止回顯 */
????tcsetattr(fileno(fp), TCSAFLUSH, &ts);
????fputs(prompt, fp);
?
????ptr = buf;
????while((c = getc(fp)) != EOF && c != '/n')
????????if(ptr < &buf[MAX_PASS_LEN])
????????????*ptr++ = c;
????*ptr = 0;????/* null terminate */
????putc('/n', fp);????/* we echo a newline */
?
????tcsetattr(fileno(fp), TCSAFLUSH, &ots);????/* restore TTY state */
????sigprocmask(SIG_SETMASK, &osig, NULL);????/* restore mask */
????fclose(fp);????/* done with /dev/tty */
????return(buf);
}
?
程序清單18-9 調用getpass函數
#include "apue.h"
?
char????*getpass(const char *);
?
int
main(void)
{
????char *ptr;
????
????if((ptr = getpass("Enter passWord:")) == NULL)
????????err_sys("getpass error");
????printf("password: %s/n", ptr);
?
????while(*ptr != 0)
????????*ptr++ = 0;????/* zero it out when we're done with it */
????exit(0);
}
?
禁止回顯運行效果:
不禁止回顯的運行效果:
新聞熱點
疑難解答