[2个SIGINT处理程序在一秒钟内收到第二个SIGINT之后退出程序

问题描述 投票:0回答:1

我的程序应该每秒输出一个从0到10的数字,并且永远不会大于10。我将它放在While(1)的主循环中以永久地进行打印。

我有一个SIGINT处理函数,分别将SIGINT和SIGTERM的数字增加1或-1。

我正在尝试实现第二个处理程序以在第一次退出程序的一秒钟内捕获第二个SIGINT信号,但是从未达到我的第二个处理程序(sig_handler_2)。我究竟做错了什么?

源代码:

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

int number = 0;

void sig_handler_2(int sig) {
    printf("Exiting the program now \n");
    signal(SIGINT, SIG_DFL);
}

void sig_handler_1(int sig) {
    signal(SIGINT, sig_handler_2);
    if (sig == SIGINT) {
        if (number > 9) {
        printf(" SIGINT received but number is > 9, cannot increment \n");
        }
      else {
          printf(" SIGINT received: Increment is now %d \n", number);
      }
    }
    if (sig == SIGTERM) {
      if (number <= 0) {
          printf(" SIGTERM received but number <= 0, cannot increment \n");
      }
      else {
          number --;
          printf(" SIGTERM received: Increment is now %d \n", number);
          printf("%d \n", number);
      }
    }
}

int main() {
    while (1) {
        signal(SIGINT, sig_handler_1);
        signal(SIGTERM, sig_handler_1);
        if (number > 9) {
            printf("%d \n", number);
            number = 0;
        }
        else {
            printf("%d \n", number);
            number ++;
        }
        sleep(1);
    }
}`
signals void sigint
1个回答
0
投票

更新:我在sig_handler_1中添加了sleep(1),它现在捕获了第二个SIGINT并输入sig_handler_2。现在可以使用了,但是我仍然觉得我没有按照“正确”的方式进行操作。还有什么想法吗?

© www.soinside.com 2019 - 2024. All rights reserved.