C: SIGALRM - alarm to display message every second

前端 未结 5 1144
北荒
北荒 2020-12-03 08:53

So I\'m trying to call an alarm to display a message \"still working..\" every second. I included signal.h.

Outside of my main I have my function: (I never declare/d

5条回答
  •  一个人的身影
    2020-12-03 09:29

    Signal handlers are not supposed to contain "business logic" or make library calls such as printf. See C11 §7.1.4/4 and its footnote:

    Thus, a signal handler cannot, in general, call standard library functions.

    All the signal handler should do is set a flag to be acted upon by non-interrupt code, and unblock a waiting system call. This program runs correctly and does not risk crashing, even if some I/O or other functionality were added:

    #include 
    #include 
    #include 
    #include 
    
    volatile sig_atomic_t print_flag = false;
    
    void handle_alarm( int sig ) {
        print_flag = true;
    }
    
    int main() {
        signal( SIGALRM, handle_alarm ); // Install handler first,
        alarm( 1 ); // before scheduling it to be called.
        for (;;) {
            sleep( 5 ); // Pretend to do something. Could also be read() or select().
            if ( print_flag ) {
                printf( "Hello\n" );
                print_flag = false;
                alarm( 1 ); // Reschedule.
            }
        }
    }
    

提交回复
热议问题