2014-02-12 37 views
0

我有我想用来处理不同信号的代码。我不知道为什么它永远不会去timer_handler2()。它只是坚持timer_handler()。有人可以告诉我我做错了什么不使用多个信号处理程序的代码

#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; 
} 
+0

代码太多!你能制作一个更简单的例子吗? –

+0

@OliCharlesworth我减少了代码 –

+0

Cool。现在阅读起来更容易!谢谢。 –

回答

0

你让程序运行多久了? ITIMER_VIRTUAL只在程序实际使用处理器时间时递减。由于你的程序大多只是在睡觉,所以不会占用太多的处理器时间。要验证,请使用unix'time'命令(或您的OS等效项)来查看程序使用的实际,用户和系统时间。我只会打赌真正的时间足以激活一个计时器。你可以尝试使你的VIRTUAL和PROF定时器的间隔更小,或者做一些不会在你的死循环中阻塞的东西(例如:删除睡眠(1))。