2017-10-12 73 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