简体   繁体   English

如何将getpass()与poll()一起使用来设置时间限制?

[英]How to use getpass() with poll() to set time limit?

I am using poll() along with getpass() to get input from user in limited time. 我正在使用poll()以及getpass()在有限的时间内从用户那里获取输入。 It works, but instead of showing message given in getpass() , it doesn't shows message until pressing enter key . 它可以正常工作,但与其显示getpass()给出的message ,不显示message直到按enter key How can I use these two functions together so that message given in getpass() will be displayed without need to enter enter key , and time to enter password will be limited? 如何将这两个函数一起使用,以便显示getpass()给出的message而无需输入enter key ,并且输入密码的时间将受到限制?

I tried to solve this by clearing stdin and stdout , but it did't work. 我试图通过清除stdinstdout来解决此问题,但这没有用。

#include <poll.h>
struct pollfd mypoll = { STDIN_FILENO, POLLIN|POLLPRI };
if( poll(&mypoll, 1, 20000) )
{
    char *pass = getpass("\nPlease enter password:");
}

getpass function is obsolete. getpass函数已过时。 Do not use it. 不要使用它。

Here is the working example. 这是工作示例。 The program wait for 20 seconds. 程序等待20秒。 If user enters password in 20 seconds then program reads information to password otherwise inform user about time exceeded to enter password.The following example does not tunoff echo. 如果用户在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;
}

The following example will turnoff echo. 以下示例将关闭回显。 Works same as getpass. 与getpass相同。 This works on linux/macosx, a windows version should use Get/Set ConsoleMode 这适用于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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM