linux 下 signal 与sigaction 对信号的处理差异

signal(SIGINT,sig_proc); 自动屏蔽了waitpid时的SIGINT信号,即waitpid时,SIGINT信号不会中断waitpid调用。

而sigaction 则需要用下列方法才可以做到同等效果:

struct sigaction sa,oldsa;


sa.sa_flags = 0;
sa.sa_handler = sig_child;
sigemptyset(&sa.sa_mask);

int n = sigaction(SIGINT,&sa,&oldsa);
if(n == -1){
perror("sigaction error");
exit(1);
}

sigaddset(&sa.sa_mask,SIGINT);
sigprocmask(SIG_BLOCK,&sa.sa_mask,NULL);


测试代码如下:

#include
#include
#include
#include
#include


void sig_child(int sig){
if(sig == SIGCHLD){
printf("have catched SIGCHLD signal\n");
}
if(sig == SIGINT){
printf("have catched SIGINT signal\n");
}
}


int main(int argc,char** argv){

signal(SIGCHLD,sig_child);
//signal(SIGINT,sig_child);
struct sigaction sa,oldsa;
sa.sa_flags = 0;
sa.sa_handler = sig_child;
sigemptyset(&sa.sa_mask);

int n = sigaction(SIGINT,&sa,&oldsa);
if(n == -1){
perror("sigaction error");
exit(2);
}

sigaddset(&sa.sa_mask,SIGINT);
sigprocmask(SIG_BLOCK,&sa.sa_mask,NULL);


pid_t pid;
pid = fork();
if(pid<0){
perror("fork error");
exit(1);
}
if(pid == 0){
signal(SIGINT,SIG_IGN);
printf("child process runing ...\n");
sleep(3);
exit(0);
}
int st = 0;
while(waitpid(pid,&st,0)!=pid){
if(errno == EINTR){
printf("waitpid catched SIGINT signal\n");
continue;
}
perror("waitpid error");
exit(2);
}


printf("waitpid ok\n");


return 0;
}

你可能感兴趣的:(linu,c)