信号编程
#include <signal.h>
#include <stdio.h>
// typedef void (*sighandler_t)(int);
// sighandler_t signal(int signum, sighandler_t handler);
void handler(int signum)
{
printf(“get signum= %d\n”,signum);
switch(signum) {
case 2:
printf(“SIGINT\n”);
break;
case 9:
printf(“SIGKILL\n”);
break;
case 10:
printf(“SIGUSR1\n”);
break;
}
printf(“never quit\n”);
}
int main()
{
signal(SIGINT,handler);
signal(SIGKILL,handler);
signal(SIGUSR1,handler);
while(1);
return 0;
}
2.软件编程实现捕捉信号
第一种方式:
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
// typedef void (*sighandler_t)(int);
// sighandler_t signal(int signum, sighandler_t handler);
int main(int argc,char **argv)
{
int signum;
int pid;
signum = atoi(argv[1]);
pid = atoi(argv[2]);
printf("signum = %d,pid = %d\n",signum,pid);
kill(pid,signum);
printf("send signal ok\n");
return 0;
}
第二种方式:
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
// typedef void (*sighandler_t)(int);
// sighandler_t signal(int signum, sighandler_t handler);
int main(int argc,char **argv)
{
int signum;
int pid;
char cmd[128];
signum = atoi(argv[1]);
pid = atoi(argv[2]);
printf("signum = %d,pid = %d\n",signum,pid);
// kill(pid,signum);
sprintf(cmd,“kill %d %d”,signum,pid);
system(cmd);
printf(“send signal ok\n”);
return 0;
}