如何在几秒钟后终止scanf?

EDG*_*INA 2 c linux posix signals

我正在使用 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 

           
Run Code Online (Sandbox Code Playgroud)

Die*_*Epp 5

你快到了\xe2\x80\x94先设置闹钟,然后scanf再打电话。read()该信号将中断对inside 的调用scanf(),从而导致scanf()立即返回。

\n
volatile int alarm_flag = 0;\nvoid setflag(int sig) {\n    alarm_flag = 1;\n}\n\n...\n\nstruct sigaction act = {};\nact.sa_handler = set_flag;\nsigaction(SIGALRM, &act, NULL);\n\n...\n\n    alarm(NSECS);\n    scanf("%s", name);\n    if (alarm_flag) {\n        ...\n
Run Code Online (Sandbox Code Playgroud)\n

一些注意事项:

\n
    \n
  • alarm_flag应该volatile

    \n
  • \n
  • setflag应该采用一个int参数。

    \n
  • \n
  • 将您的功能声明为func(void)not func()。从 1990 年左右开始,将函数声明func()为老式风格,现在使用它没有任何好处。(请注意,C++ 是不同的。)

    \n
  • \n
\n

更多注意事项:

\n
    \n
  • 您不应该使用== TRUE== FALSE。在这种特殊情况下,它可能工作正常,但在某些情况下它不能\xe2\x80\x99t。所以我几乎永远不会使用== TRUE.

    \n
  • \n
  • 作为练习,此代码alarm是合理的,但如果您想在生产应用程序中执行此类操作,您可能会使用类似的东西libuv而不是alarm(). \xe2\x80\x99s 并不是这种方法有问题,只是使用非阻塞 IO 并且libuv可能更容易处理。

    \n
  • \n
\n