Sample
Sample

Reputation: 1

Interrupt in C++

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

Upvotes: 0

Views: 3121

Answers (1)

Bill Lynch
Bill Lynch

Reputation: 81916

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;
}

Upvotes: 2

Related Questions