c - 使用 getpass() 后,我无法再在 linux 命令提示符中输入内容。它正在记录我的击键,但不回显它们

标签 c linux signals echo alarm

  signal(SIGALRM, handler);
  alarm(5);
  passphrase = getpass("Enter Passphrase:");
  alarm(0);
  exit(0);


void handler(int sig)
{
  if(sig == SIGALRM)
    printf("<Time Out> \n");
  exit(0);
}

这是我的代码片段。 5 秒后超时,它打印 timeout 并且下一个命令提示符出现 $,但它不再回显我输入的内容。但是它正在记录它,如果输入正确,我仍然可以执行命令

最佳答案

毫无疑问 getpass (顺便说一句,您不应该使用1)正在修改终端设置以不回显密码,这也毫无疑问如果允许完成,则重新打开回显。

但是,由于您在此之前中断了它,因此您可能必须自己恢复设置,使用类似 tcsetattr() 的内容。 .

作为示例,请参阅以下程序:

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

// For saving terminal status.

static struct termios tio;

static void handler (int sig) {
    // Notify user, reset term status and exit.

    printf("<Time Out>\n");
    tcsetattr(0, TCSANOW, &tio);

    exit (0);
}

int main (void) {
    char *passphrase;

    // Save terminal setting, probably
    //   need better error handling :-)

    if (tcgetattr(0, &tio) != 0) {
        printf ("urk!\n");
    }

    // Start timer, try to get input.

    signal (SIGALRM, handler);
    alarm (5);
    passphrase = getpass ("Enter Passphrase: ");
    alarm (0);

    // Print it and finish up.

    printf ("You entered '%s'\n", passphrase);

    return 0;
}
<小时/>

1 它在 Linux 中已被标记为过时,并且不久前已从 POSIX 中删除。如果您想知道在 getpass()首选项中使用什么,答案就在上面的代码中。将 tcsetattr()ECHO 选项结合使用(请记住,您的信号处理程序仍应在退出时恢复)。

关于c - 使用 getpass() 后,我无法再在 linux 命令提示符中输入内容。它正在记录我的击键,但不回显它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29688947/

相关文章:

c - 在 c 中读取用户输入末尾的换行符

python - 如何制作一个用CFFI包裹的C-DLL来回调python

c - 在循环中执行多个管道

c++ - Linux 3.0 : futex-lock deadlock bug?

c - sigprocmask 之后 sigset_t 的值

c - 对树使用回溯

C - for 循环仅执行 scanf 之后的循环

linux - Bash 脚本 - 遍历关联数组列表的 "variable"变量名

android - 如何根据信号强度按升序对 getScanResults() 列表进行排序?

c - 为什么子进程不回复父进程发送的信号?