2017-10-12 58 views
2
void signal_handler(int signo) 
{ 
    struct sigaction act; 

    if ((sigaction(signo, NULL, &act) == -1) || (act.sa_handler != SIG_IGN)) 
    { 
     alarm(50); 
    } 

} 

int main() 
{ 
    sigaction(SIGINT,signal_handler); 
    sigaction(SIGALAM,signal_handler); 
    alarm(50); 

    while (1) 
    { 
    } 
    return 0; 
} 

我想在开始的50秒内忽略Ctrl + C信号。我试着用它报警,但不忽略信号。如何忽略前50秒的信号?

回答

2

这些都是你需要遵循acheive您两端的步骤:

  • 设置SIGINTSIG_IGNmain开始。
  • 然后设置SIGALARM以调用不同的处理程序(50秒后)。
  • 在该处理程序中,更改SIGINT,以便它现在指向实际处理程序。

这应该忽略SIGINT第一个五十秒左右的中断,然后再对它们采取行动。


下面是一个完整的程序,显示了这一行动。它基本上执行上面详述的步骤,但是对于测试程序稍作修改:

  • 开始忽略INT
  • 设置ALRM在十秒后激活。
  • 开始每秒生成INT信号20秒。
  • 当警报激活时,停止忽略INT

的程序是:

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

static time_t base, now; // Used for tracking time. 

// Signal handlers. 

void int_handler(int unused) { 
    // Just log the event. 

    printf(" - Handling INT at t=%ld\n", now - base); 
} 

void alarm_handler(int unused) { 
    // Change SIGINT handler from ignore to actual. 

    struct sigaction actn; 
    actn.sa_flags = 0; 
    actn.sa_handler = int_handler; 
    sigaction(SIGINT, &actn, NULL); 
} 

int main(void) 
{ 
    base = time(0); 

    struct sigaction actn; 

    // Initially ignore INT. 

    actn.sa_flags = 0; 
    actn.sa_handler = SIG_IGN; 
    sigaction(SIGINT, &actn, NULL); 

    // Set ALRM so that it enables INT handling, then start timer. 

    actn.sa_flags = 0; 
    actn.sa_handler = alarm_handler; 
    sigaction(SIGALRM, &actn, NULL); 
    alarm(10); 

    // Just loop, generating one INT per second. 

    for (int i = 0; i < 20; ++i) 
    { 
     now = time(0); 
     printf("Generating INT at t=%ld\n", now - base); 
     raise(SIGINT); 
     sleep(1); 
    } 

    return 0; 
} 

这里有我的盒子输出,使您可以在行动中看到它,忽略INT信号的前十秒钟,然后对他们采取行动:

Generating INT at t=0 
Generating INT at t=1 
Generating INT at t=2 
Generating INT at t=3 
Generating INT at t=4 
Generating INT at t=5 
Generating INT at t=6 
Generating INT at t=7 
Generating INT at t=8 
Generating INT at t=9 
Generating INT at t=10 
    - Handling INT at t=10 
Generating INT at t=11 
    - Handling INT at t=11 
Generating INT at t=12 
    - Handling INT at t=12 
Generating INT at t=13 
    - Handling INT at t=13 
Generating INT at t=14 
    - Handling INT at t=14 
Generating INT at t=15 
    - Handling INT at t=15 
Generating INT at t=16 
    - Handling INT at t=16 
Generating INT at t=17 
    - Handling INT at t=17 
Generating INT at t=18 
    - Handling INT at t=18 
Generating INT at t=19 
    - Handling INT at t=19 
+0

我需要在'void signal_handler(int signo)'中进行任何更改吗? – JKLM

+0

你能告诉我代码吗? – JKLM

+0

@Saurabh,添加了一些代码,希望更清楚。享受:-) – paxdiablo