如何在超时后跳过输入,继续执行C语言代码?
实现C语言限时用户输入的两种方法
要实现超时后跳过用户输入继续执行,核心是先设置超时等待,再判断是否有输入可读——你原代码里先阻塞等待输入再sleep的逻辑是反的,无法实现超时跳过的需求。下面是两种适用于POSIX系统(Linux、macOS等)的可行方案:
方法一:使用select()函数监听输入
select()可以监听文件描述符的可读状态,同时设置超时时间。如果在超时前标准输入(stdin)有数据,就读取输入;否则直接进入超时逻辑。
#include <stdio.h> #include <sys/select.h> #include <unistd.h> int main() { printf("How old are you? (You have 5 seconds to input)\n"); fd_set read_fds; FD_ZERO(&read_fds); FD_SET(STDIN_FILENO, &read_fds); // 设置超时时间为5秒 struct timeval timeout; timeout.tv_sec = 5; timeout.tv_usec = 0; // 监听stdin是否可读 int result = select(STDIN_FILENO + 1, &read_fds, NULL, NULL, &timeout); if (result == -1) { perror("select error"); return 1; } else if (result == 0) { // 超时:没有输入 printf("\nIt seems like the user is not there\n\nGoodbye\n"); return 1; } else { // 有输入,读取数据 int age; if (scanf("%d", &age) == 1) { printf("You are %d years old\n", age); } else { printf("Invalid input\n"); } return 0; } }
方法二:使用alarm()信号实现超时
通过设置alarm()在指定时间后触发SIGALRM信号,在信号处理函数中标记超时状态,中断阻塞的scanf后,在主逻辑中判断是否超时。
#include <stdio.h> #include <signal.h> #include <unistd.h> volatile int timed_out = 0; // SIGALRM信号处理函数 void timeout_handler(int sig) { timed_out = 1; } int main() { printf("How old are you? (You have 5 seconds to input)\n"); // 注册信号处理函数 signal(SIGALRM, timeout_handler); // 设置5秒后触发闹钟信号 alarm(5); int age; // 读取输入,若被信号中断则返回-1 int ret = scanf("%d", &age); // 关闭闹钟(如果用户提前输入) alarm(0); if (timed_out) { printf("\nIt seems like the user is not there\n\nGoodbye\n"); return 1; } else if (ret == 1) { printf("You are %d years old\n", age); return 0; } else { printf("Invalid input\n"); return 1; } }
注意事项
- 以上两种方法仅适用于POSIX兼容系统,Windows平台需要使用不同的API(例如
SetConsoleMode修改控制台模式,配合WaitForSingleObject等待输入事件)。 - 若用户输入了部分字符但未回车,超时后这些字符会留在输入缓冲区中,后续程序运行可能受影响,必要时可额外清理缓冲区。
内容的提问来源于stack exchange,提问作者Joki_004
相关产品推荐
相关产品推荐

