Pages

Monday, December 23, 2013

Catching Linux signals - Example C program

Did a quick test on a strip down Linux machine to make sure the basics are in tact before troubleshooting a C program with signal handlers. This simple program triggers an alarm signal at a predetermined time. Just to make sure it has not stalled, a while loop is used to print the remaining time for the signal to trigger.    

 

#include <stdio.h>

#include <signal.h>

void handle(int sig)

{

   switch (sig)

   {

      case SIGALRM:

         printf("\nAlarm triggered\n");

         break;

      default:

         break;

   }

}



int main(int argc, char * argv[]) {

   int ticks = 10;

   signal(SIGALRM, handle);

   if (argc == 1)

   {

      printf("Using default alarm time: 10 seconds\n");

   }

   else

   {

      ticks = strtol(argv[1], NULL, 10);

      printf("Using alarm time: %d second(s)\n", ticks);

   }

   //Schedule alarm

   alarm(ticks);

   //Print remaining time

   while(ticks > 0)

   {

       printf("\r%02d", ticks);

   

       //Should call this function to display tick before sleeping.

       //Otherwise the request is buffered.

       fflush(stdout);

       ticks--;

       sleep(1);

   }

 

   //Cancel pending alarm requests, if any.

   alarm(0);

   printf("\ndone\n");



   return 0;

} 


No comments:

Post a Comment