简体   繁体   中英

Code not making using of more than one signal handler

I have this code that I want to use to handle different signals. I don't know why it never goes to timer_handler2(). It just sticks on timer_handler(). Could someone kindly tell me what I am doing wrong

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

struct timeval theTime;
static int count = 0;

void timer_handler2(int signum) {   
    printf("timer 2 expired %d times\n", ++count);  
}

void timer_handler(int signum) {    
    printf("timer 1 expired %d times\n", ++count);  
}

void timer_handler3(int signum) {

    printf("timer 3 expired %d times\n", ++count);
}

int main() {
    struct itimerval timer, timer2, timer3, got;    

    signal(SIGVTALRM, timer_handler2);
    signal(SIGALRM, timer_handler);
    signal(SIGPROF, timer_handler3);

    /* ... and every 1000 msec after that.  */
    timer2.it_interval.tv_sec = 1;
    timer2.it_interval.tv_usec = 0;
    /* Configure the timer to expire after 1000 msec...  */
    timer2.it_value.tv_sec = 1;
    timer2.it_value.tv_usec = 0;

    /* ... and every 1000 msec after that.  */
    timer.it_interval.tv_sec = 0;
    timer.it_interval.tv_usec = 0;
    /* Configure the timer to expire after 1000 msec...  */
    timer.it_value.tv_sec = 1;
    timer.it_value.tv_usec = 250000;

    /* ... and every 1000 msec after that.  */
    timer3.it_interval.tv_sec = 1;
    timer3.it_interval.tv_usec = 0;
    /* Configure the timer to expire after 1000 msec...  */
    timer3.it_value.tv_sec = 1;
    timer3.it_value.tv_usec = 0;

    /* Start a real timer. It counts down whenever this process is
     executing.  */
    setitimer(ITIMER_VIRTUAL, &timer2, NULL);
    setitimer(ITIMER_REAL, &timer, NULL);
    setitimer(ITIMER_PROF, &timer3, NULL);

    int counter = 0;
    while (1) {
        sleep(1);
        counter++;
    }

    return 0;
}

How long are you letting the program run? ITIMER_VIRTUAL only decrements when the program is actually using processor time. Since your program is mostly just sleeping, it's not going to use much processor time. To verify, use the unix 'time' command (or your OS equivalent) to see the real, user and system time used by the program. I'll bet only the real time is enough to activate a timer.

You can try making your VIRTUAL and PROF timer intervals (much) smaller, or do something that doesn't block in your infinite loop (ie: remove the sleep(1) ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM