我正在使用 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 …Run Code Online (Sandbox Code Playgroud)