Linux提供了一组编程接口,用来控制终端驱动程序的行为。这样我们可以更精细的来控制终端。

例如:

回显:允许控制字符的回显,例如读取密码时。

使用termios结构的密码程序

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

#define LENGTH 8

char passwd[LENGTH];

int main()
{

    struct termios initsettings;
    struct termios newsettings;

    printf("input your password\n");

    tcgetattr(fileno(stdin), &initsettings);

    newsettings = initsettings;
    newsettings.c_lflag &= ~ECHO;

    tcsetattr(fileno(stdin), TCSAFLUSH, &newsettings);

    fgets(passwd, LENGTH, stdin);

    tcsetattr(fileno(stdin), TCSANOW, &initsettings);

    fprintf(stdout, "your passwd is:");
    fprintf(stdout, "%s", passwd);

    return 0;

}

注意,在程序关闭结束之前,要恢复终端的原始设置。

 ----------------------------------------------------------------------

在非标准模式下,默认的回车和换行符之间的映射已经不存在了。'\n' 回车  '\r' 换行。

----------------------------------------------------------------------

当用户按下ctrl + c 组合键时,程序将终止。可以在本地模式下清除ISIG标志来禁用这些特殊字符的处理。

    newsettings = initsettings;
    newsettings.c_lflag &= ~ICANON;//关闭标准输入处理

    newsettings.c_lflag &= ~ECHO;//关闭回显功能

//一键入字符,fgetc立刻返回,不用按下回车键,

    newsettings.c_cc[VMIN] = 1;

    newsettings.c_cc[VTIME] = 0;

//禁用ctrl+c组合键,(按键按下时产生特殊字符?)

    newsettings.c_lflag &= ~ISIG;

 

posted on 2016-03-30 17:12  邶风  阅读(956)  评论(0编辑  收藏  举报