Linux中的信号处理

来源:互联网 发布:二手车的价格怎么算法 编辑:程序博客网 时间:2024/04/28 03:02
突然想起使用sigaction注册信号处理函数时,信号处理函数类型有二个:
  1. struct sigaction
  2. {
  3.       void (*sa_handler)(int);
  4.       void (*sa_sigaction)(int, siginfo_t *, void *);
  5.       sigset_t sa_mask;
  6.       int sa_flags;
  7.       void (*sa_restorer)(void);
  8. };

通过对上面的sa_flags赋值为SA_SIGINFO,让系统使用多参数的信号处理函数。在处理函数中,由于传进来一个siginfo_t的参数,我们可以通过它获取到哪个进程传进来的消息。

今天试了下,有点问题,在产生信号时,应当调用注册的信号处理函数,但此时,报出段错误,去除注册信号处理函数那行,一切OK。所以断定系统在调用信号处理函数时发生错误。网上查找相关资料也没有看到原因,故此记下来,继续寻找答案。(注:如果使用sa_handler,完全没有问题)

  1.  #include <stdlib.h>
  2.  #include <unistd.h>
  3.  #include <signal.h>
  4.  #include <errno.h>
  5.  #include <string.h>
  6.  #include <stdio.h>
  7.  #include <sys/types.h>
  8.  void child_process_exit_handle(int signo,siginfo_t *info, void *context);
  9.  int main(int argc, char **argv)
  10.  {
  11.      struct sigaction new_action , old_action;
  12.      memset(&new_action,0,sizeof(new_action));
  13.      memset(&old_action,0,sizeof(old_action));
  14.      new_action.sa_sigaction = child_process_exit_handle;
  15.      sigemptyset(&new_action.sa_mask);
  16.      new_action.sa_flags = SA_SIGINFO;
  17.      sigaction(SIGCHLD,&new_action,&old_action);
  18.      puts("output before vfork!");
  19.     pid_t child_pid = fork();
  20.      if(child_pid < 0)
  21.      {
  22.         printf(strerror(errno));
  23.          return -1;
  24.     }
  25.      else if(child_pid == 0)
  26.      {
  27.         printf("In the Child Process!/n");
  28.         _exit(0);
  29.      }
  30.      printf("Do nothing!/n");
  31.       int ch = 0x00;
  32.       while(ch = getchar(),ch != 'q'){}
  33.      
  34.       sigaction(SIGCHLD,&old_action,&new_action);
  35.       return 1;
  36.  }
  37.  void child_process_exit_handle(int signo, siginfo_t *info, void *context)
  38.  {
  39.      int state;
  40.      printf("child process %d exit!/n",info->si_pid);
  41.     pid_t pid = waitpid(info->si_pid,&state,0);
  42.     if(pid < 0 )
  43.          printf("Wait process exit failured!/n");
  44.  }
原创粉丝点击