我正在使用poll()
和getpass()
在有限的时间内从用户那里获得输入。它有效,但在message
中没有显示getpass()
,而是在按message
之前不会显示enter key
。如何将这两个功能结合使用,以便message
中显示getpass()
,而无需输入enter key
,输入密码的时间将受到限制?
我尝试通过清除stdin
和stdout
来解决此问题,但它确实无效。
#include <poll.h>
struct pollfd mypoll = { STDIN_FILENO, POLLIN|POLLPRI };
if( poll(&mypoll, 1, 20000) )
{
char *pass = getpass("\nPlease enter password:");
}
答案 0 :(得分:1)
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;
}