我可以在 C 中使用 sigaction 的标志 siginfo 和 SIGCHLD 获取终止进程的信号 int 常量(如 SIGINT 或 SIGKILL)吗?

Can i get the signal int constant (like SIGINT or SIGKILL) that terminated a process using using sigaction's flag siginfo with SIGCHLD in C?

我正在尝试确定是否可以使用传递给标志设置为 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 来完成吗?

问题已解决。

新片段:

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代码来识别进程的异常中断。