0

我试图弄清楚我是否可以使用传递给标志设置为 SA_SIGINFO 的 sigaction 的自定义 SIGCHLD 处理程序来获得终止子进程的信号。据我了解,si_status 应该根据 si_code 值报告退出值或信号值。

这是 SIGCHLD 处理程序的代码:

static void sigchdl (int sig, siginfo_t *siginfo, void *context)
{

  int code = siginfo -> si_code, status = siginfo -> si_status;

      if(code == CLD_EXITED) 
      if(WIFEXITED(status)) printf("the background command with PID: %ld                               has been successfull\n,(long)siginfo>si_pid);

      else if(code == CLD_KILLED) {

       //2 = SIGINT, 9 = SIGKILL, 15 = SIGTERM (man signal)

      if(WTERMSIG(status) == 2 || WTERMSIG(status) == 9 || WTERMSIG(status) == 15)

      printf("Il comando in background con PID: %ld e' stato terminato dal segnale %d, chiamato           da: %d\n", (long)siginfo->si_pid, siginfo -> si_status, getpid());

      else

       perror("Command terminated abnormally\n"); 
       
      } 
   
}

现在我的问题是,首先:可以这样做吗?

第二:如果是,我可以使用 si_status 和 si_code 吗?

4

1 回答 1

0

问题已解决。

新片段:

static void sigchdl (int sig, siginfo_t *siginfo, void *context)
{


  int code = siginfo -> si_code, status = siginfo -> si_status;

      printf("si_code: %d\n", code);
      printf("si_status: %d\n", status);


      if(code == CLD_EXITED) { if(WIFEXITED(status)) printf("Il comando in background con PID: %ld e' terminato normalmente\n",
            (long)siginfo->si_pid); }

      else if(code == CLD_KILLED) {

       //2 = SIGINT, 9 = SIGKILL, 15 = SIGTERM

      if(status == 2 || status == 9 || status == 15)

      printf("Il comando in background con PID: %ld e' stato terminato dal segnale %d, chiamato da: %d\n",
            (long)siginfo->si_pid, siginfo -> si_status, getpid());


      }

      else if(code == CLD_DUMPED) perror("il comando è terminato in modo anormale \n"); 

}

问题在于 WTERMSIG 导致在比赛中毫无用处。 状态已经保持信号恒定值。仍然需要 si_code 检查来识别“由信号终止”的情况。

还添加了 CLD_DUMPED 代码以识别进程的异常中断。

于 2020-09-08T09:57:29.880 回答