linux - sigtimedwait() 的 "set"参数中的信号未传送

标签 linux signals signal-handling sigaction sigprocmask

我最近一直在研究 Linux 上的信号处理,并阅读了所有与信号处理相关的概念。一个困扰我的问题是,为什么在进程畅通无阻时,sigtimedwait() 集合中的信号没有被传递。我的代码如下:-

#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
void sighandler1(int sig)
{
        printf("SIGINT caught\n");
}
void sighandler2(int sig)
{
        printf("SIGTSTP caught\n");
}
void sighandler3(int sig)
{
        printf("SIGALRM caught\n");
}

int main()
{

  sigset_t s1,s2;

  struct sigaction act1,act2,act3;

  int ret;

  sigemptyset(&s1);// The bit-mask s1 is cleared
  sigaddset(&s1,SIGINT);//Add SIGINT to the bit-mask s1

  sigemptyset(&s2);// The bit-mask s2 is cleared
  sigaddset(&s2,SIGALRM);//Add SIGALRM to the bit-mask s2

  sigprocmask(SIG_BLOCK,&s2,NULL);//Signal(s) in s2 blocked

  act1.sa_handler = sighandler1; //function pointer pointing to the signal handler
  act1.sa_flags = 0;        

  sigaction(SIGINT,&act1,NULL);  // installing the action
                                 // for SIGINT

  act2.sa_handler = sighandler2; //function pointer pointing to another signal handler
  act2.sa_flags = 0;         // no flags


  sigaction(SIGTSTP,&act2,NULL);  // installing the action
                                 // for SIGTSTP
  act3.sa_handler = sighandler3; //function pointer pointing to another signal handler
  act3.sa_flags = 0;         // no flags


  sigaction(SIGALRM,&act3,NULL);  // installing the action for SIGALRM

  sigprocmask(SIG_SETMASK,&s1,NULL); //Signals in s1 blocked and other signals unblocked
  printf("sigprocmask() called with SIG_SETMASK on s1,which contains SIGINT\n");
  printf("Blocked on sigtimedwait() with s1\n");
  if(sigtimedwait(&s1,NULL,NULL) < 0)
        {
                if(errno ==  EINTR)
                printf("Some other signal caught\n");
        }
  printf("This is a process. You can pass signal to it\n");

  while(1);

}

为了更清楚地说明问题,我在上面的代码中调用了 sigtimedwait,并将“s1”作为“set”参数。该集合仅包含信号 SIGINT。根据手册页,sigtimedwait() 会阻塞进程,直到传递其集合中的一个信号。我完全同意这种说法。但是为什么当我通过 SIGINT 来解锁进程时没有调用 SIGINT 处理程序?另一方面,当我传递集合中不存在的 SIGALRM 或 SIGTSTP 时,会按预期返回 EINTR,并且还会调用信号处理程序。

对于任何想观察场景的人,都可以执行上面的代码,然后将 SIGINT 传递给它。他们将观察到进程在没有调用处理程序的情况下畅通无阻。为什么不调用处理程序?我是否误解了 sigtimedwait() 手册页的任何部分??

最佳答案

sigtimedwait 似乎返回信号值,而不是信号处理程序被捕获:

switch(sigtimedwait(&s1,NULL,NULL))
{
    default:
        printf ("Some other signal???");
        break;
    case SIGINT:
        printf ("We got SIGINT\n");
        break;
    case -1:
        perror ("sigtimedwait");
        break;
}

关于linux - sigtimedwait() 的 "set"参数中的信号未传送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36675011/

相关文章:

linux - 部署地理服务器 WAR 后,Tomcat 未在浏览器上加载 - Ubuntu

直接从新信号处理程序调用默认信号处理程序

c++ - FFTW信号频谱

c - Kill() 错误 : no such process?

c - 接收到用户定义的信号时,进程不会取消暂停

perl - 为 fork() 的守护进程管理信号处理

c - 如何编写信号处理程序来捕获 SIGSEGV?

linux - 如何开始使用 Linux 进行 Web 开发?

c - 当等待进程(在信号量队列中)收到来自另一个进程的信号时会发生什么?

c - 如何链接内核模块来使用它们的功能?