【问题标题】:Code not making using of more than one signal handler代码不使用多个信号处理程序
【发布时间】:2014-03-10 12:34:40
【问题描述】:

我有这段代码,我想用它来处理不同的信号。我不知道为什么它永远不会进入 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;
}

【问题讨论】:

  • 代码太多!你能举一个更简单的例子吗?
  • @OliCharlesworth 我已经减少了代码
  • 酷。现在更容易阅读了!谢谢。
  • don't use printf in signal handler 你是在连续向同一个进程发送信号吗?

标签: c signals setitimer


【解决方案1】:

您让程序运行多长时间? ITIMER_VIRTUAL 仅在程序实际使用处理器时间时递减。由于您的程序大多只是在休眠,因此不会占用太多处理器时间。要进行验证,请使用 unix 'time' 命令(或您的操作系统等效命令)查看程序使用的真实时间、用户时间和系统时间。我敢打赌只有实时时间就足以激活计时器。

您可以尝试使您的 VIRTUAL 和 PROF 计时器间隔(大大)更小,或者做一些不会在您的无限循环中阻塞的事情(即:移除 sleep(1) )。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    相关资源
    最近更新 更多