Unix/Linux 信号处理示例程序
Unix/Linux 信号处理示例程序
1.简单的信号处理程序
- #include <unistd.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <signal.h>
- static void sig_usr(int);
- typedef void Sigfunc(int);
- Sigfunc *signal(int,Sigfunc *);
- int main(int argc,char **argv)
- {
- if(signal(SIGUSR1,sig_usr) == SIG_ERR){
- fprintf(stderr,"Error!\n");
- exit(-1);
- }
- if(signal(SIGUSR2,sig_usr) == SIG_ERR){
- fprintf(stderr,"Error!\n");
- exit(-1);
- }
- while(1)
- pause();
- }
- static void sig_usr(int signo)
- {
- if(signo == SIGUSR1)
- printf("received SIGUSR1!\n");
- if(signo == SIGUSR2)
- printf("received SIGUSR2!\n");
- else
- printf("received signal %d\n",signo);
- }
后台执行,.然后使用kill命令来发送信号。
- <strong>$ ./a.out &</strong>
- [1] 7216
- <strong>$ kill -USR1 7216
- </strong>received SIGUSR1
- <strong>$ kill -USR2 7216</strong>
- received SIGUSR2
- <strong>$ kill 7216
- </strong>[1]+ Terminated ./a.out
2.调用不可重入函数的示例程序
- #include <unistd.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <signal.h>
- typedef void Sigfunc(int);
- Sigfunc *signal(int,Sigfunc *);
- static void my_alarm(int signo)
- {
- struct passwd *rootptr;
- printf("in signal handle\n");
- if((rootptr = getpwnam("root")) == NULL){
- printf("error!\n");
- exit(-1);
- }
- alarm(1);
- }
- int main(int argc,char **argv)
- {
- struct passwd *ptr;
- signal(SIGALRM,my_alarm);
- alarm(1);
- for(;;){
- if((ptr = getpwnam("leon")) == NULL)
- err_sys("getpwnam error");
- if(strcmp(ptr->pw_name,"leon") != 0)
- printf("return value corrupted!,pw_name = %s\n",ptr->pw_name);
- }
- }
评论暂时关闭