這些都是你需要遵循acheive您兩端的步驟:
- 設置
SIGINT
到SIG_IGN
時main
開始。
- 然後設置
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
我需要在'void signal_handler(int signo)'中進行任何更改嗎? – JKLM
你能告訴我代碼嗎? – JKLM
@Saurabh,添加了一些代碼,希望更清楚。享受:-) – paxdiablo