getpass 函数已过时。不要使用它。
这是一个工作示例。程序等待 20 秒。如果用户在 20 秒内输入密码,则程序会读取密码信息,否则会通知用户输入密码超时。以下示例不会关闭回显。
#include <unistd.h>
#include <poll.h>
#include <stdio.h>
int main()
{
struct pollfd mypoll = { STDIN_FILENO, POLLIN|POLLPRI };
char password[100];
printf("Please enter password\n");
if( poll(&mypoll, 1, 20000) )
{
scanf("%99s", password);
printf("password - %s\n", password);
}
else
{
puts("Time Up");
}
return 0;
}
以下示例将关闭回声。与 getpass 相同。这适用于 linux/macosx,windows 版本应该使用Get/Set ConsoleMode
#include <unistd.h>
#include <poll.h>
#include <stdio.h>
#include <termios.h>
#include <stdlib.h>
int main()
{
struct pollfd mypoll = { STDIN_FILENO, POLLIN|POLLPRI };
char password[100];
struct termios oflags, nflags;
/* disabling echo */
tcgetattr(fileno(stdin), &oflags);
nflags = oflags;
nflags.c_lflag &= ~ECHO;
nflags.c_lflag |= ECHONL;
if (tcsetattr(fileno(stdin), TCSANOW, &nflags) != 0) {
perror("tcsetattr");
return EXIT_FAILURE;
}
printf("Please enter password\n");
if( poll(&mypoll, 1, 20000) )
{
scanf("%s", password);
printf("password - %s\n", password);
}
else
{
puts("Time Up");
}
/* restore terminal */
if (tcsetattr(fileno(stdin), TCSANOW, &oflags) != 0) {
perror("tcsetattr");
return EXIT_FAILURE;
}
return 0;
}