本文介绍了从`stdin`读取时如何添加超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要检查用户是否花费了超过3000ms的时间在 stdin 上进行输入.
I need to check if the user took more than 3000ms to give input on stdin.
有没有办法在等待用户输入时添加超时?像
Is there a way to add a timeout when waiting for user input? Something like
if (timeout) { // do something } else { // do something else } 推荐答案下面的程序将从超时的 stdin 中读取,这是您想要的.
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; }更多推荐
从`stdin`读取时如何添加超时
发布评论