5.4.1 termios结构,关闭回显功能,一键入字符fgetc立刻返回,不用按下回车键

本文介绍了如何使用Linux编程接口控制终端行为,包括禁止密码回显、禁用Ctrl+C默认行为等高级技巧。通过示例代码展示了如何修改termios结构来实现这些功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

 

转载于:https://www.cnblogs.com/zhangxuan/p/5337981.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值