简体   繁体   English

如何在几秒钟后终止 scanf?

[英]How to terminate scanf after a few seconds?

I'm using signals in C language.我正在使用 C 语言中的信号。 The program consists in wait a few seconds for a user keyboard input if the time ends, the program terminates.该程序包括等待几秒钟以等待用户键盘输入,如果时间结束,则程序终止。 However, I always have to enter text although time was over if not the program never ends.但是,我总是必须输入文本,尽管时间已经结束,否则程序永远不会结束。 Is there any way to avoid scanf?有什么办法可以避免scanf?

Here is my code这是我的代码

#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 

           

You are almost there—set the alarm first, and call scanf afterwards.你就快到了——先设置闹钟,然后再调用scanf The signal will interrupt the call to read() inside scanf() , which causes scanf() to return immediately.该信号将中断scanf()内部对read()的调用,这会导致scanf()立即返回。

volatile int alarm_flag = 0;
void setflag(int sig) {
    alarm_flag = 1;
}

...

struct sigaction act = {};
act.sa_handler = set_flag;
sigaction(SIGALRM, &act, NULL);

...

    alarm(NSECS);
    scanf("%s", name);
    if (alarm_flag) {
        ...

A couple notes:一些注意事项:

  • alarm_flag should be volatile . alarm_flag应该是volatile

  • setflag should take one int parameter. setflag应该采用一个int参数。

  • Declare your functions as func(void) not func() .将您的函数声明为func(void)而不是func() Declaring a function as func() is an old-fashioned style from before 1990 or so and there is no benefit to using it today.将函数声明为func()是 1990 年左右之前的老式风格,今天使用它没有任何好处。 (Note that C++ is different.) (请注意,C++ 是不同的。)

More notes:更多注意事项:

  • You should not use == TRUE or == FALSE .你不应该使用== TRUE== FALSE In this particular case it may work fine, but there are cases where it doesn't.在这种特殊情况下,它可能会正常工作,但在某些情况下却不会。 So I would almost never use == TRUE .所以我几乎不会使用== TRUE

  • As an exercise this code with alarm is reasonable, but if you want to do this kind of thing in a production application you would probably use something like libuv instead of alarm() .作为练习,这段带有alarm代码是合理的,但如果你想在生产应用程序中做这种事情,你可能会使用libuv之类的libuv而不是alarm() It's not that there's something wrong with this approach, just that using non-blocking IO and libuv would probably be easier to deal with.并不是这种方法有什么问题,只是使用非阻塞 IO 和libuv可能更容易处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM