C 如何在读取'stdin'时添加超时`

C 如何在读取'stdin'时添加超时`,c,if-statement,C,If Statement,我需要检查用户在标准输入上输入的时间是否超过3000毫秒 在等待用户输入时是否有方法添加超时?差不多 if (timeout) { // do something } else { // do something else } 下面的程序将通过超时从stdin读取数据,这是您想要的 #include <stdio.h> #include <unistd.h> #include <sys/select.h> #define LEN 100 int

我需要检查用户在标准输入上输入的时间是否超过3000毫秒

在等待用户输入时是否有方法添加超时?差不多

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

下面的程序将通过超时从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;
}

返回值:如果请求的时间已过,则为零;如果呼叫被信号处理程序中断,则为剩余睡眠秒数。“不工作”不是正确的问题描述。复杂的你能给我举个例子吗?我明白,但我没有制定这个计划的最低想法。我的问题很小,很客观,所以我甚至没有输入大代码。你想实现什么?进行3次打印;否则printfno就毫无意义了。