Unix/Linux 信号处理示例程序


1.简单的信号处理程序

  1. #include <unistd.h>   
  2. #include <stdlib.h>   
  3. #include <stdio.h>   
  4. #include <signal.h>   
  5.   
  6. static  void sig_usr(int);  
  7. typedef void Sigfunc(int);  
  8. Sigfunc *signal(int,Sigfunc *);  
  9.   
  10. int main(int argc,char **argv)  
  11. {  
  12.     if(signal(SIGUSR1,sig_usr) == SIG_ERR){  
  13.         fprintf(stderr,"Error!\n");  
  14.         exit(-1);  
  15.     }  
  16.     if(signal(SIGUSR2,sig_usr) == SIG_ERR){  
  17.         fprintf(stderr,"Error!\n");  
  18.         exit(-1);  
  19.     }  
  20.   
  21.     while(1)  
  22.         pause();  
  23. }  
  24.   
  25. static void sig_usr(int signo)  
  26. {  
  27.     if(signo == SIGUSR1)  
  28.         printf("received SIGUSR1!\n");  
  29.     if(signo == SIGUSR2)  
  30.         printf("received SIGUSR2!\n");  
  31.     else  
  32.         printf("received signal %d\n",signo);  
  33. }  

后台执行,.然后使用kill命令来发送信号。

  1. <strong>$ ./a.out &</strong>  
  2. [1]    7216  
  3. <strong>$ kill -USR1 7216  
  4. </strong>received SIGUSR1  
  5. <strong>$ kill -USR2 7216</strong>  
  6. received SIGUSR2  
  7. <strong>$ kill 7216  
  8. </strong>[1]+  Terminated    ./a.out  

2.调用不可重入函数的示例程序

  1. #include <unistd.h>   
  2. #include <stdlib.h>   
  3. #include <stdio.h>   
  4. #include <signal.h>   
  5.   
  6. typedef void Sigfunc(int);  
  7. Sigfunc *signal(int,Sigfunc *);  
  8.   
  9. static void my_alarm(int signo)  
  10. {  
  11.     struct passwd   *rootptr;  
  12.   
  13.     printf("in signal handle\n");  
  14.     if((rootptr = getpwnam("root")) == NULL){  
  15.         printf("error!\n");  
  16.         exit(-1);  
  17.     }  
  18.     alarm(1);  
  19. }  
  20. int main(int argc,char **argv)  
  21. {  
  22.     struct passwd   *ptr;  
  23.   
  24.     signal(SIGALRM,my_alarm);  
  25.     alarm(1);  
  26.     for(;;){  
  27.         if((ptr = getpwnam("leon")) == NULL)  
  28.             err_sys("getpwnam error");  
  29.         if(strcmp(ptr->pw_name,"leon") != 0)  
  30.             printf("return value corrupted!,pw_name = %s\n",ptr->pw_name);  
  31.     }  
  32. }  

相关内容