忽略信号:对信号置之不理
捕捉信号:改变信号的行为
缺省方式:按信号的默认行为来做
SIGCHLD 是子进程状态改变发给父进程的。
kill -l 查看所有的信号
kill -9 pid 无条件杀死一个进程
signal函数可以改变信号的默认行为。
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <linux/posix_types.h>
typedef void (*sighandler_t)(int);
sighandler_t oldact;
void handle(int sig){
printf("I cath the SIGINT \n");
// signal(SIGINT,oldact);//捕捉信号,执行oldact
}
int main(){
oldact = signal(SIGINT,handle);//捕捉信号,执行handle
while(1){
sleep(1);
}
}
struct sigaction结构体介绍
struct sigaction {
void (*sa_handler)(int);
void (*sa_sigaction)(int, siginfo_t *, void *);
sigset_t sa_mask;
int sa_flags;
void (*sa_restorer)(void);
}
使用信号捕捉实现了一个定时器功能。
功能:5秒钟后,每秒发送一次second timer信号。
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <linux/posix_types.h>
#include <sys/time.h>
typedef void (*sighandler_t)(int);
sighandler_t oldact;
void handle(int sig){
if(sig == SIGINT){
printf("I cath the SIGINT \n");
}else if (sig==SIGALRM){
printf("second timer \n");
}
}
int main(){
struct sigaction act;
act.sa_handler = handle;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);//清空信号集
struct itimerval timevalue;
timevalue.it_interval.tv_sec = 1;//闹钟触发周期为1秒
timevalue.it_interval.tv_usec = 0;
timevalue.it_value.tv_sec = 5;//闹钟触发时间为5秒
timevalue.it_value.tv_usec = 0;
setitimer(ITIMER_REAL,&timevalue, NULL);
sigaction(SIGALRM,&act,NULL);
while(1){
}
}
SIGCHLD信号配合wait函数来回收子进程:
#include <stdio.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
void handle(int sig){
wait(NULL);
printf("Get sig =%d\n",sig);
}
int main(){
pid_t pid;
struct sigaction act;
act.sa_handler = handle;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
pid = fork();
if(pid>0){
//wait(NULL);
sigaction(SIGCHLD,&act,NULL);
while(1){
printf("this is father process\n");
sleep(1);
}
}else if(pid==0){
sleep(5);
exit(0);
}
}