Monday, September 29, 2025

QNX: Running a function at specific interval using timer interrupt

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

void timer_handler(int signo) {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    char buf[100];
    struct tm* nowtm;
    nowtm = localtime(&tv.tv_sec);
    strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", nowtm);
    printf("Timer expired at %s.%03ld\n", buf, tv.tv_usec / 1000);
}

int main() {
    timer_t timerid;
    struct sigevent sev;
    struct itimerspec its;
    struct sigaction sa;

    // Install the timer handler
    sa.sa_flags = 0;
    sa.sa_handler = timer_handler;
    sigemptyset(&sa.sa_mask);
    if (sigaction(SIGRTMIN, &sa, NULL) == -1) {
        std::cerr << "sigaction: " << errno << std::endl;
        return -1;
    }

    // Create the timer
    sev.sigev_notify = SIGEV_SIGNAL;
    sev.sigev_signo = SIGRTMIN;
    if (timer_create(CLOCK_REALTIME, &sev, &timerid) == -1) {
        std::cerr << "timer_create: " << errno << std::endl;
        return -1;
    }

    // Set the timer to expire every second
    its.it_value.tv_sec = 1;
    its.it_value.tv_nsec = 0;
    its.it_interval.tv_sec = 1;
    its.it_interval.tv_nsec = 0;
    if (timer_settime(timerid, 0, &its, NULL) == -1) {
        std::cerr << "timer_settime: " << errno << std::endl;
        return -1;
    }

    // Main loop
    while (true) {
        pause(); // Wait for signals
    }

    return 0;
}

No comments:

CPP Quick Guide

Basics Hello world User input While loop If statement For loop Switch statement Read file using ifstream Write to a file using ofstr...