views:

95

answers:

1

Hi, I am trying to understand interrupts and am looking for a simple code that uses interrupts. Could somebody please help me with it?

+1  A: 

Here are two examples using the alarm function. alarm causes SIGALRM to happen n seconds after you call that function.

This program will run for 3 seconds, and then die with SIGALRM.

#include <signal.h>
#include <unistd.h>

int main() {
    alarm(3);
    while(true);
}

In this case, we'd like to catch SIGALRM, and die gracefully with a message:

#include <signal.h>
#include <unistd.h>
#include <iostream>

volatile bool alarmed = false;

void alrm_handler(int) {
    alarmed = true;
}

int main() {
    signal(SIGALRM, alrm_handler);

    alarm(3);
    while(not alarmed);

    std::cout << "done" << std::endl;
}
sharth
Thank you!! =))
Sample
I tried to use ualarm instead of alarm now but it doesn't seem to be working. :( The code looks like: #include <signal.h>#include <unistd.h>#include <iostream>volatile bool alarmed = false;void alrm_handler(int) { alarmed = true;}int main() { signal(SIGALRM, alrm_handler); ualarm(3000000, 0); while(not alarmed); std::cout << "done" << std::endl;}
Sample
From the man page of ualarm, the first argument must be less than 1000000. See: http://www.kernel.org/doc/man-pages/online/pages/man3/ualarm.3.html
sharth