[Solved] How to add a timeout when reading from `stdin` [closed]


The following program will read from stdin with a timeout, which is what you want.

#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;
}

solved How to add a timeout when reading from `stdin` [closed]