实例一:如何使用信号函数捕捉相应的信号,并做相应的处理。
- /*
- * signal.c
- *
- * Created on: 2012-7-19
- * Author: liwei.cai
- */
- #include <signal.h>
- #include <stdio.h>
- #include <stdlib.h>
- //自定义信号处理函数
- void my_func(int sign_no)
- {
- if (sign_no == SIGINT)
- {
- printf("I have get SIGINT\n"); //Ctrl + C
- }
- else if (sign_no == SIGQUIT)
- {
- printf("I hava get SIGQUIT\n");//Ctrl + \
- }
- }
- //int main()
- //{
- // printf("Waiting for signal SIGINT or SIGQUIT..\n");
- // //发出相应的信号,并跳到信号处理函数处
- // signal(SIGINT,my_func);
- // signal(SIGQUIT,my_func);
- // pause();
- // exit(0);
- //}
- int main()
- {
- struct sigaction action;
- printf("Waiting for signal SIGINT or SIGQUIT>>>\n");
- //sigaction结构初始化
- action.sa_handler = my_func;
- sigemptyset(&action.sa_mask);
- action.sa_flags = 0;
- //发出相应的信号,并跳转到信号处理函数处
- sigaction(SIGINT, &action,0);
- sigaction(SIGQUIT, &action, 0);
- pause();
- exit(0);
- }
- /*
- * sigset.c
- *
- * Created on: 2012-7-20
- * Author: liwei.cai
- */
- #include <sys/types.h>
- #include <unistd.h>
- #include <signal.h>
- #include <stdio.h>
- #include <stdlib.h>
- //自定义的信号处理函数
- void my_func(int signum)
- {
- printf("IF you want to quit, please try SIGUIT\n");
- }
- int main()
- {
- sigset_t set, pendset;
- struct sigaction action1, action2;
- //初始化信号集为空
- if (sigemptyset(&set) < 0)
- {
- perror("sigemptyset");
- exit(1);
- }
- //将相应的信号加入到信号集
- if(sigaddset(&set, SIGQUIT) < 0)
- {
- perror("sigaddset");
- exit(1);
- }
- if(sigaddset(&set, SIGINT) < 0)
- {
- perror("sigaddset");
- exit(1);
- }
- if(sigismember(&set, SIGINT))
- {
- sigemptyset(&action1.sa_mask);
- action1.sa_handler = my_func;
- action1.sa_flags = 0;
- sigaction(SIGINT, &action1, NULL);
- }
- if(sigismember(&set, SIGQUIT))
- {
- sigemptyset(&action2.sa_mask);
- action2.sa_handler = my_func;
- action2.sa_flags = 0;
- sigaction(SIGINT, &action2, NULL);
- }
- //设置信号集屏蔽字,此时set中的信号不会被传递给进程,暂时进入待处理状态
- if (sigprocmask(SIG_BLOCK, &set, NULL) < 0)
- {
- perror("sigprocmask");
- exit(1);
- }
- else
- {
- printf("Signal set was blocked, Press any key!");
- getchar();
- }
- //在信号屏蔽字中删除set中的信号
- if (sigprocmask(SIG_UNBLOCK, &set, NULL) < 0)
- {
- perror("sigprocmask");
- exit(1);
- }
- else
- {
- printf("Signal set is in unblock state!");
- getchar();
- }
- while(1);
- exit(0);
- }