一、信号处理函数的注册 signal()使用:
1 #include<stdio.h>2 #include <signal.h>3 4 void handler(int signum)5 {6 switch(signum){7 case 2:8 printf("signum = %d\n",signum);9 break;10 case 9:11 printf("signum = %d\n",signum);12 break;13 case 10:14 printf("signum = %d\n",signum);15 break;16 }17 }18 19 int main()20 {21 signal(SIGINT,handler);22 signal(SIGKILL,handler);23 signal(SIGUSR1,handler);24 25 while(1);26 27 return 0;28 }
二、信号处理发送函数kill()
刚才都是通过kill指令发信号,现在写个程序完成信号的发送
1 #include<stdio.h>2 #include<stdlib.h>3 #include <signal.h>4 //int kill(pid_t pid, int sig);5 6 int main(int argc ,char *argv[])7 {8 int signum;9 int pid;10 11 signum=atoi(argv[1]);12 pid =atoi(argv[2]);13 printf("signum=%d,pid=%d\n",signum,pid);14 15 kill(pid,signum);16 printf("kill ok\n");17 return 0;18 }
三、或者用system()调用脚本来杀
1 #include<stdio.h>2 #include <stdlib.h>3 //int system(const char *command);4 5 int main(int argc,char *argv[])6 {7 int sig;8 int pid;9 sig = atoi(argv[1]);10 pid = atoi(argv[2]);11 printf("sig=%d,pid=%d\n",sig,pid);12 13 char cmd[32]={0};14 sprintf(cmd,"kill -%d %d",sig,pid);15 system(cmd);16 return 0;17 }
~
四、信号携带消息----高级信号编程
vi demo16.c
1 #include<stdio.h>2 #include<signal.h>3 #include <unistd.h>4 //int sigaction(int signum, const struct sigaction *restrict act,5 // struct sigaction *restrict oldact);6 7 void handler(int sig, siginfo_t *info, void *ucontext)8 {9 printf("sig=%d\n",sig);10 if(ucontext!=NULL){11 printf("data =%d\n",info->si_int);12 printf("send pid =%d\n",info->si_pid);13 }14 15 }16 17 18 int main()19 {20 struct sigaction act;21 act.sa_flags = SA_SIGINFO;22 act.sa_sigaction = handler;23 24 printf("read pid=%d\n",getpid());25 sigaction(SIGUSR2,&act,NULL);26 while(1);27 return 0;28 }
vi demo17.c
1 #include <unistd.h>2 #include<stdio.h>3 #include<stdlib.h>4 #include <signal.h>5 6 //int system(const char *command);7 //int sigqueue(pid_t pid, int sig, const union sigval value);8 int main(int argc,char *argv[])9 {10 int sig;11 int pid;12 sig = atoi(argv[1]);13 pid = atoi(argv[2]);14 printf("sig=%d,pid=%d\n",sig,pid);15 16 union sigval value;17 value.sival_int = 77;18 printf("my pid is %d\n",getpid());19 sigqueue(pid,sig,value);20 printf("send ok\n");21 return 0;22 }
~