从`stdin`读取时如何添加超时

编程入门 行业动态 更新时间:2024-10-23 18:31:31
本文介绍了从`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`读取时如何添加超时

本文发布于:2023-07-06 07:56:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047583.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:stdin

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!