$ cat ../apue.h
#ifndef _APUE_H_
#define _APUE_H_
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <assert.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>
#include <signal.h>
void err_exit(char *m){
perror(m);
exit(EXIT_FAILURE);
}
案例一:收到信號後會立即處理
#include "./apue.h"
void handler(int sig){
printf("sig=%d\n", sig);
}
int main(void){
struct sigaction act; //信號結構體
act.sa_handler=handler; //收到信號後調用的信號處理函數
sigemptyset(&act.sa_mask);
act.sa_flags=0;
if(sigaction(SIGINT, &act, NULL)<0){
err_exit("sigaction error\n");
}
for(;;)
pause();
return 0;
}
案例二:收到信號SIGQUIT後,等上一個信號SIGINT處理完畢再處理
#include "./apue.h"
void handler(int sig){
printf("sig=%d\n", sig);
sleep(3);
}
int main(void){
struct sigaction act;
act.sa_handler=handler;
sigemptyset(&act.sa_mask);
sigaddset(&act.sa_mask, SIGQUIT);
act.sa_flags=0;
if(sigaction(SIGINT, &act, NULL)<0){
err_exit("sigaction error\n");
}
for(;;)
pause();
return 0;
}
介紹一些函數:
sigemptyset 函數初始化信號集合set,將set 設置爲空.
sigfillset 也初始化信號集合,只是將信號集合設置爲所有信號的集合.
sigaddset 將信號signo 加入到信號集合之中,sigdelset 將信號從信號集合中刪除.
sigismember 查詢信號是否在信號集合之中.s
igprocmask 是最爲關鍵的一個函數.在使用之前要先設置好信號集合set.這個函數的作用是將指定的信號集合set 加入到進程的信號阻塞集合之中去,如果提供了oset 那麼當前的進程信號阻塞集合將會保存在oset 裏面.參數how 決定函數的操作方式:
SIG_BLOCK:增加一個信號集合到當前進程的阻塞集合之中.
SIG_UNBLOCK:從當前的阻塞集合之中刪除一個信號集合.
SIG_SETMASK:將當前的信號集合設置爲信號阻塞集合.