进程之间的信号响应 关于进程之间的信号处理的函数有signal,kill,raise signal函数用于设置该进程对于某种信号的处理方式 kill函数用于进程主动发送某中信号给某个进程组或进程 下面的程序父进程创建了一个子进程,两个进程双方交互发送信号, 信号处理函数记录每个进程被通知的次数 #include <signal.h> #include <stdio.h> #include <stdlib.h> int ntimes=0; int main() { int pid,ppid; int f_action(),s_action(); //set SIGUSR1 of father process //SIGNAL1 SIGNAL2 is signal which user defines himself signal(SIGUSR1,f_action); pid=fork(); switch(pid) { case -1: perror("synchro"); exit(1); case 0: //code in son process //set SIGUSR1 of son process signal(SIGUSR1,s_action); //get id of father process ppid=getppid(); for(;;) { sleep(1); //the kill function can be used to send any signal to any process group or group kill(ppid,SIGUSR1); pause(); } break; default: //code in father process for(;;) { pause(); sleep(1); kill(pid,SIGUSR1); } } } int f_action() { printf("Father counts %d/n",++ntimes); return 1; } int s_action() { printf("Son counts %d/n",++ntimes); return 1; } 抓取信号的简单程序 例子中演示了抓取中断信号(SIGINT) 然后进入自己的处理过程:catch #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <signal.h> int main() { int catch(int sig); printf("Try to catch/n"); signal(SIGINT,catch); sleep(10); printf("End of the program./n"); return 0; } int catch(int sig) { printf("This is catch!/n"); return 0; } 中断信号屏蔽 该例子中使用signal函数中的设置 使用参数SIG_IGN屏蔽SIGINT 即:屏蔽中断信号(CTRL+C) 然后在通过判断逻辑来恢复原先的信号处理机制 #include <stdlib.h> #include <stdio.h> #include <signal.h> int main() { char c; signal(SIGINT,SIG_IGN); printf("Try to use Ctrl+c to stop me!/n"); printf("Do you want to recovery to reviece the signal int(y/n)?"); scanf("%c",&c); if(c=='y' | c=='Y') { signal(SIGINT,SIG_DFL); } sleep(10); printf("end"); return 0; }