在 Linux C 守护程序中设置信号掩码

Setting up signal masks in a Linux C daemon

我在 Linux 上 运行 用 C 编写了一个简单的守护程序。我试图了解如何正确设置信号掩码。我的守护进程中有以下代码:

struct sigaction new_sig_action;
sigset_t new_sig_set;

/* Set signal mask - signals we want to block */
sigemptyset(&new_sig_set);
sigaddset(&new_sig_set, SIGCHLD);  /* ignore child - i.e. we don't need to wait for it */
sigaddset(&new_sig_set, SIGTSTP);  /* ignore Tty stop signals */
sigaddset(&new_sig_set, SIGTTOU);  /* ignore Tty background writes */
sigaddset(&new_sig_set, SIGTTIN);  /* ignore Tty background reads */
sigprocmask(SIG_BLOCK, &new_sig_set, NULL);   /* Block the above specified signals */

/* Set up a signal handler */
new_sig_action.sa_handler = signal_handler;
sigemptyset(&new_sig_action.sa_mask);
new_sig_action.sa_flags = 0;

/* Signals to handle */
sigaction(SIGHUP, &new_sig_action, NULL);     /* catch hangup signal */
sigaction(SIGTERM, &new_sig_action, NULL);    /* catch term signal */
sigaction(SIGINT, &new_sig_action, NULL);     /* catch interrupt signal */

其中 signal_handler 是定义的函数。我在停止守护进程时遇到问题,如 thread.

中所述

我现在已经跟踪到当守护程序在不同环境(同一用户,同一系统)中启动时块掩码不同的问题。从命令行启动守护程序会产生以下 'ps' 输出:

> ps -C powid -o pid,ppid,command,blocked,caught,ignored
PID  PPID COMMAND                              BLOCKED           CAUGHT      IGNORED
11406     1 ./powid                     0000000000390000 0000000180004003 0000000000000000

并且当通过 PHP 脚本启动完全相同的守护进程时,产生:

> ps -C powid -o pid,ppid,command,blocked,caught,ignored                           
PID  PPID COMMAND                             BLOCKED           CAUGHT        IGNORED
11491     1 ./powid                     fffffffe3bfbe207 0000000180004003 00000000010010

我的问题是,为什么屏蔽的掩码不一样。我的理解表明给定的 C 代码会强制阻止的掩码在所有条件下都相同?

libc documentation 状态:

Each process has its own signal mask. When you create a new process (see Creating a Process), it inherits its parent’s mask.

所以为什么被屏蔽的掩码不同的答案是因为 parents 曾经有不同的掩码...

您给定的 C 代码 添加 一些信号到阻止列表,因为您使用 sigprocmask 并将第一个参数设置为 SIG_BLOCK。如果要覆盖信号掩码,请使用 SIG_SETMASK。这样,您应该得到一个 parent 独立信号块掩码。