【问题标题】:How to add a timeout when reading from `stdin` [closed]从`stdin`读取时如何添加超时[关闭]
【发布时间】:2018-08-19 00:23:31
【问题描述】:

我需要检查用户在stdin 上提供输入的时间是否超过 3000 毫秒。

有没有办法在等待用户输入时添加超时?类似的东西

if (timeout) {
  // do something
} else {
  // do something else
}

【问题讨论】:

  • "返回值:如果请求的时间已经过去,则返回零;如果调用被信号处理程序中断,则剩余的休眠秒数。" linux.die.net/man/3/sleep
  • “不起作用”不是正确的问题描述。精心制作的。并提供minimal reproducible example
  • 你能举个例子吗?我明白,但没有最小的想法来制作这个程序。
  • 我的问题小而客观,所以我什至没有输入大代码。
  • 你想达到什么目的?做if(sleep(3)) printf("yes"); else printf("no") 绝对没有意义。

标签: c if-statement


【解决方案1】:

以下程序将从stdin 读取超时,这是您想要的。

#include <stdio.h>
#include <unistd.h>
#include <sys/select.h>

#define LEN 100

int main() {
    struct timeval timeout = {3, 0};
    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(STDIN_FILENO, &fds);
    printf("Hi. What is your name?\n");
    int ret = select(1, &fds, NULL, NULL, &timeout);
    if (ret == -1) {
        printf("Oops! Something wrong happened...\n");
    } else if (ret == 0) {
        printf("Doesn't matter. You're too slow!\n");
    } else {
        char name[LEN];
        fgets(name, LEN, stdin);
        printf("Nice to meet you, %s\n", name);
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 2010-12-18
    • 1970-01-01
    相关资源
    最近更新 更多