【发布时间】:2020-10-14 02:22:39
【问题描述】:
我在 C 语言中使用信号。该程序包括等待几秒钟以等待用户键盘输入,如果时间结束,则程序终止。但是,我总是必须输入文本,尽管时间已经结束,否则程序永远不会结束。有什么办法可以避免scanf?
这是我的代码
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <stdlib.h>
#define NSECS 10
#define TRUE 1
#define FALSE 0
# define BELLS "\007\007\007"
int alarm_flag = FALSE;
void bye(){
printf("Good bye...");
}
void setflag(){
alarm_flag = TRUE;
}
int main() {
char name[20];
do {
printf("File name: \n");
scanf("%s", name);
signal(SIGALRM, setflag);
alarm(NSECS);
if (alarm_flag == TRUE){
printf(BELLS);
atexit(adios);
return 0;
} // if the user enters a file name, the program continues
【问题讨论】:
-
请添加操作系统标签。
-
@Joshua:我不确定是否有合适的标签——类 Unix?
-
@DietrichEpp:有一个 posix 标签,或者他可以为他实际使用的操作系统添加标签。
-
@Joshua 已更新,感谢推荐