posix timer

是浩瀚宇宙啊發表於2024-10-10

/*
 * timr.c
 *
 *  Created on: May 11, 2024
 *      Author: 
 */


#include <signal.h>
       #include <stdint.h>
       #include <stdio.h>
       #include <stdlib.h>
       #include <time.h>
       #include <unistd.h>

       #define CLOCKID CLOCK_REALTIME
       #define SIG SIGRTMIN

       #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
                               } while (0)



void timer_callback(union sigval v)
{
    printf("timer_callback!\n");
}

int main(void)
{
    timer_t timerid;
    struct sigevent sev;
    sev.sigev_notify = SIGEV_THREAD;
    sev.sigev_value.sival_ptr = &timerid;
    sev.sigev_notify_function = timer_callback;
    sev.sigev_notify_attributes = NULL;

    if (timer_create(CLOCK_REALTIME, &sev, &timerid) == -1) {
        perror("timer_create");
        return 1;
    }

    struct itimerspec its;
    its.it_value.tv_sec =0;
    its.it_value.tv_nsec = 9;
    its.it_interval.tv_sec = 3;
    its.it_interval.tv_nsec = its.it_value.tv_nsec;

    if (timer_settime(timerid, 0, &its, NULL) == -1) {
        perror("timer_settime");
        return 1;
    }
    while(1);
}

相關文章