1

I am trying to study how signal handlers work. I have written code where i cause an alarm signal to raise once in every 100us. But, the signal is not raised. Here is the code :

 #include <signal.h>
 #include <ucontext.h>
 #include <sys/time.h>
 #include<unistd.h>
 #include<setjmp.h>
 #include<stdio.h>

void handler(int signum, siginfo_t *ptr, ucontext_t *old_context)
{
    printf("inside handler");
}

int main()
{
 struct itimerval itv;
 struct sigaction act;
 act.sa_handler = handler;
 act.sa_flags=SA_RESTART|SA_SIGINFO;
 sigaction(SIGVTALRM, &act, 0);
 itv.it_interval.tv_sec=0;
 itv.it_interval.tv_usec=100;
 itv.it_value.tv_sec = 0;
 itv.it_value.tv_usec = 100;          

 setitimer(ITIMER_VIRTUAL, &itv, NULL); //engage timer
 int i=0;
 while(i<=100)
 {
    printf("main\n");
    i++;
 }  
}

can some one explain what i am doing wrong?

Thanks

curiousguy
  • 8,038
  • 2
  • 40
  • 58
CuriousCoder
  • 1,582
  • 5
  • 28
  • 55

1 Answers1

2

Your loop is probably taking less than 100us to run, try this:

volatile int i=0;
while(i<=100000000)
{
    //printf("main\n");
    i++;
}

I removed the printf so the output is not flooded, and made i volatile so the compiler won't optimize the loop.

fbafelipe
  • 4,862
  • 2
  • 25
  • 40