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/