C: SIGALRM - alarm to display message every second

前端 未结 5 1141
北荒
北荒 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:10

    Do not call alarm() twice, just call it once in main() to initiate the callback, then once in display_message(). Try this code on Linux (Debian 7.8) :

    #include  
    #include  
    
    void display_message(int s);   //Function for alarm set up
    
    void display_message(int s)
    {
         printf("copyit: Still working...\n" );
         alarm(1);    //for every second
         signal(SIGALRM, display_message);
    }
    
    int main()
    {
        signal(SIGALRM, display_message);
        alarm(1);     // Initial timeout setting
    
         while (1) 
         {   
              pause();
         }   
    }
    

    The result will be the following one :

    copyit: Still working...
    copyit: Still working...
    copyit: Still working...
    copyit: Still working...
    copyit: Still working...
    copyit: Still working...
    copyit: Still working...
    copyit: Still working...
    copyit: Still working...
    copyit: Still working...
    copyit: Still working...
    copyit: Still working...
    

提交回复
热议问题