有时信号没有收到信号处理程序

时间:2017-07-30 06:42:57

标签: linux multithreading pthreads signals signal-handling

我正在连续循环发送来自终端的100信号(SIGINT),因为我有这个信号的寄存器信号处理程序,所以任何信号都来自辅助线程或主线程(因为信号处理由所有线程共享) )每次发送信号时都应该输出“catch signal:...”消息作为输出。但我观察到100,一些随机少,没有时间说95,84次是这个消息打印。有人可以解释为什么所有100个信号都没有打印,以及如何使用以下代码打印所有100个信号。

#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>

// Signal Handler for entire Process (shared by all threads) 

void signalHandler(int param)
{
  printf("Caught signal: %d ", param);
}

void *childFun(void *arg)
{
  // Register signal Handler here 
  struct sigaction childpsa;
  childpsa.sa_handler = signalHandler;
  sigaction(SIGTERM, &childpsa, NULL);
  sigaction(SIGHUP, &childpsa, NULL);
  sigaction(SIGINT, &childpsa, NULL);
  sigaction(SIGCONT, &childpsa, NULL);
  sigaction(SIGTSTP, &childpsa, NULL);

  while (1) {
    // doSomething in while loop
  }
}

int main(void)
{

  // create a auxiliary thread here
  pthread_t child_threadId;
  int err = pthread_create(&child_threadId, NULL, &childFun, NULL);

  while (1) {
    // main program do something 
  }

  return 1;
}

1 个答案:

答案 0 :(得分:0)

大多数Linux实现不支持信号排队,因此,如果一个进程多次收到相同的信号“ x”,则只会被调用一次。

此外,您不应在信号处理程序中使用诸如printf之类的功能(而应使用一些每次调用都会递增的计数器(整数))

POSIX.1允许系统在处理取消阻塞信号之前多次生成阻塞信号的情况下,一次或多次传送信号。如果系统不止一次传递信号,我们就说信号已排队。但是,大多数UNIX系统不将信号排队,除非它们支持POSIX.1的实时扩展。相反,UNIX内核仅发送一次信号。 [p336]

https://notes.shichao.io/apue/ch10/#reliable-signal-terminology-and-semantics