我有一个创建两个子进程的程序,所以,子进程1向子进程2发送sigint,子进程2处理sigint(sigint块sigusr1的处理程序),在sigint之后,子进程1向子进程2发送sigusr1。
我不知道为什么sigusr1终止了子2。sigusr1在发送sigint时被阻止。

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

sigset_t base_mask, waiting_mask;

void handler(int signum)
{
  signal(SIGINT, handler);
  sigemptyset (&base_mask);
  sigaddset (&base_mask, SIGUSR1);
  /* Block user interrupts while doing other processing. */
  if(sigprocmask (SIG_BLOCK, &base_mask, NULL) != 0)
    printf("cannot block\n");
  else
    printf("SIGUSR1 blocked\n");
  if(sigismember(&base_mask, SIGUSR1))
    printf("sigusr1 in mask\n");
}

int main()
{
 if(fork())
  {
    if(fork())
    {
      printf("parent out\n");
    }
    else//child 2
    {
      printf("i am sib 2 with pid = %d\n", getpid());
      signal(SIGINT, handler);
      pause();
      printf("before sleep\n");
      sleep(10);
      printf("after sleep\n");
      /* After a while, check to see whether any signals are pending. */
      sigpending (&waiting_mask);
      if (sigismember (&waiting_mask, SIGUSR1))
        printf("/* SIGUSR1 pending. */\n");
      sleep(2);
      printf("2 out\n");
    }
  }
  else//child 1
 {
    printf("i am sib 1 with pid = %d\n", getpid());
    sleep(2);
    printf("SIGINT to %d\n", getpid() + 1);
    if(kill(getpid() + 1, SIGINT))
      printf("Signal cannot be sent\n");
    sleep(4);
    if(kill(getpid() + 1, SIGUSR1))
      printf("Signal 2 cannot be sent\n");
    else
      printf("SIGUSR1 sent to %d\n", getpid() + 1);
    sleep(4);
  }
  return 0;
}

输出:
parent out,
i am sib 1 with pid = 2525,
i am sib 2 with pid = 2526,
SIGINT to 2526,
SIGUSR1 blocked,
sigusr1 in mask,
before sleep,
SIGUSR1 sent to 2526

最佳答案

问题是:您在信号处理程序中阻止了此信号:

void handler(int signum) {
  ...
  if(sigprocmask (SIG_BLOCK, &base_mask, NULL) != 0)
    printf("cannot block\n");
  else
    printf("SIGUSR1 blocked\n");
  if(sigismember(&base_mask, SIGUSR1))
    printf("sigusr1 in mask\n");
}

但从信号处理程序返回后,阻塞的信号掩码将恢复为它在处理程序输入时的值!因此,调用sigprocmask()只会影响当前处理程序调用期间被阻塞的信号。你必须在信号处理程序之外调用它。

关于c - SIGUSR1终止了该过程,尽管我已将其阻止,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35431643/

10-10 17:38