註冊 signal 的 handler function ---> signal(SIGALRM, helloHandler);
2秒後發送一次 SIGALRM signal ---> alarm(2);
注意!
連續呼叫 alarm
例:
alarm(1);
alarm(2);
alarm(3);
會以最後的數值為主
另外 alarm 不設定 handler 的話
alarm 發生預設處理是結束 process
You should establish a handler for the appropriate alarm signal using
signal
or sigaction
before issuing a call to
setitimer
or alarm
. Otherwise, an unusual chain of events
could cause the timer to expire before your program establishes the
handler. In this case it would be terminated, since termination is the
default action for the alarm signals.
by GNU C Library
Unix Signal Wiki
程式範例:
#include
#include
#include
#include
static int is_exit = 0;
void terminateHandler(int sig)
{
is_exit = 1;
printf("sig = %d\n", sig);
}
void helloHandler()
{
is_exit = 1;
printf("helloHandler\n");
}
int main(void) {
int i;
// asign alarm signal handler
signal(SIGALRM, helloHandler);
// terminate singal handler
// when console type #>kill alarmT PID(process ID)
signal(SIGTERM, terminateHandler);
while(!is_exit){
if (1){
alarm(1);
printf("if 1\n");
for (i = 0; i printf("sleep %d\n", i);
sleep(3);
}
}
if (1){
alarm(1);
printf("if 2\n");
sleep(3);
}
if (1){
alarm(1);
printf("if 3\n");
sleep(3);
}
}
printf("jump while\n");
return EXIT_SUCCESS;
}
- Feb 04 Sat 2012 11:29
[C/C++] Unix Signal Handle
全站熱搜
留言列表
禁止留言