colorful

zc qq:1337220912

 

Linux程序退出时的信号捕获及处理

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <string.h>  
  4. #include <sys/types.h>  
  5. #include <sys/stat.h>  
  6. #include <fcntl.h>  
  7. #include <unistd.h>  
  8. #include <signal.h>  
  1. // 程序退出时的函数操作  
  2. void test(int n,struct siginfo *siginfo,void *myact)  
  3. {  
  4.          printf("signal number:%d\n",n);/** 打印出信号值 **/  
  5.          printf("siginfo signo:%d\n",siginfo->si_signo); /** siginfo结构里保存的信号值 **/  
  6.          printf("siginfo errno:%d\n",siginfo->si_errno); /** 打印出错误代码 **/  
  7.          printf("siginfo code:%d\n",siginfo->si_code);   /** 打印出出错原因 **/  
  8.     exit(0);  
  9. }  
  10. int main(void)  
  11. {  
  12.          /** install signal use sigaction **/  
  13.          struct sigaction act;  
  14.          sigemptyset(&act.sa_mask);   /** 清空阻塞信号 **/  
  15.          act.sa_flags=SA_SIGINFO;     /** 设置SA_SIGINFO 表示传递附加信息到触发函数 **/  
  16.          act.sa_sigaction=test;  
  17.          if(sigaction(SIGINT,&act,NULL) < 0)  
  18.          {  
  19.                  printf("install signal error\n");  
  20.          }  
  21.          while(1)  
  22.          {  
  23.                  sleep(1);  
  24.                  printf("wait for the signal\n");  
  25.          }  
  26. }  

///////////////////////////////////////////////////

  • if (atexit(&cleanup)) //atexit现在不鼓励用了,常用来做程序退出的后处理工作  
  •     {  
  •         fprintf(stderr, "cannot set exit function/n");  
  •         return EXIT_FAILURE;  
  •     }  
  •     signal (SIGINT, &catch_int);  
  •     signal (SIGTERM, &catch_term);  
  • #ifdef __WIN32__  
  •     signal (SIGBREAK, &catch_break);  
  • #else  
  •     signal (SIGHUP, &catch_hup);  
  •     signal (SIGQUIT, &catch_quit);  
  • #endif


  • posted on 2012-07-22 21:22 多彩人生 阅读(1791) 评论(0)  编辑 收藏 引用


    只有注册用户登录后才能发表评论。
    网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


    导航

    统计

    常用链接

    留言簿(3)

    随笔分类

    随笔档案

    搜索

    最新评论

    阅读排行榜

    评论排行榜