1 Alarm Signals and SIGALRM
1.1 Setting an alarm
unsigned int alarm(unsigned int seconds);
- 过n秒后向进程发送
SIGALARM
信号 SIGALARM
信号默认动作是terminate
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/signal.h>
void alarm_handler(int signum){
printf("Buzz Buzz Buzz\n");
}
int main(){
//set up alarm handler
signal(SIGALRM, alarm_handler);
//schedule alarm for 1 second
alarm(1);
//do not proceed until signal is handled
pause();
}
1.2 Recurring Alarms
/* buzz_buzz.c*/
void alarm_handler(int signum){
printf("Buzz Buzz Buzz\n");
//set a new alarm for 1 second
alarm(1);
}
int main(){
//set up alarm handler
signal(SIGALRM, alarm_handler);
//schedule the first alarm
alarm(1);
//pause in a loop
while(1){
pause();
}
}
1.3 Resetting Alarms
void sigint_handler(int signum){
printf("Snoozing!\n");
//schedule next alarm for 5 seconds
alarm(5);
}
void alarm_handler(int signum){
printf("Buzz Buzz Buzz\n");
//set a new alarm for 1 second
alarm(1);
}
int main(){
//set up alarm handler
signal(SIGALRM, alarm_handler);
//set up signint handler
signal(SIGINT, sigint_handler);
//schedule the first alarm
alarm(1);
//pause in a loop
while(1){
pause();
}
}
2 sigaction() and Reentrant Functions
2.1 sigaction()
1.int sigaction(int signum, const struct sigaction *act,struct sigaction *oldact);
2.
struct sigaction {
void (*sa_handler)(int);
void (*sa_sigaction)(int, siginfo_t *, void *);
sigset_t sa_mask;
int sa_flags;
};
void handler(int signum){
printf("Hello World!\n");
}
int main(){
//declare a struct sigaction
struct sigaction action;
//set the handler
action.sa_handler = handler;
//call sigaction with the action structure
sigaction(SIGALRM, &action, NULL);
//schedule an alarm
alarm(1);
//pause
pause();
}