Monday, April 23, 2018

Catching SIGALRM Signal: Self-driven using alarm function

What makes SIGALRM signal something special?  It is generally used with alarm function.
It is similar to raise function, except for 2 things
  1. SIGALRM is the only signal generated out of alarm function
  2. The signal is not raised immediately.  It is raised after some delay, that is specified by user.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

void alarm_catch(int signum)
{
 printf("\tCaught the signal %d\n",signum);
}

void main()
{
 //Registering SIGALRM signal
 signal(SIGALRM,alarm_catch);

 //Raise SIGALRM signal to same process after 3 seconds
 alarm(3);

 //Timer loop for 5 seconds: Each print message denotes one second passed
 for(int i=0;i<5;i++)
 {
  printf("TIME\n");
  fflush(stdout);
  sleep(1);
 }
 
}
Steps will be like this
  1. Registering the signal 
  2. Raising alarm.(To raise SIGALRM after 3 seconds)
  3. Timer Loop for 5 seconds
After alarm function is executed, next line of code will be executed without any delay. In the background, after 3 seconds SIGALRM would have been raised.
When we execute the program


root@kali:~# ./a.out
TIME
TIME
TIME
 Caught the signal 14
TIME
TIME

 We got 'Caught the signal 14'(alarm_catch function is executed) after 3 TIME messages (3 seconds, argument of alarm).

No comments:

Post a Comment