在 C 中发送信号?

Sending Signals in C?

我阅读了:

There are two signals that a process can’t ignore – SIGKILL = terminate the receiving process – SIGSTOP = suspend the receiving process

有些人甚至声称我们无法为他们声明处理程序

但在 C 中我可以写:

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

void sigint_handler(int signum) {
    printf("I'm ignoring you!\n");
}

int main() {
    signal(SIGKILL,sigint_handler);
    for(;;) { /*endless loop*/ } return 0;
}

这不是自相矛盾吗?

附带问题,当我在终端中写入 kill 123 时,将发送什么信号?我在互联网上的任何地方都找不到此信息吗?

POSIX-1.2017 General Information §2.4.3 Signal Actions ,信号在传递给进程时可能具有三种不同的处置或“采取的行动”之一:

  • SIG_DFL:采取默认或“正常”操作。
  • SIG_IGN: 忽略信号(不采取任何行动)。
  • 用户定义:信号被用户定义的信号处理程序“捕获”。

也就是说,POSIX的同一节也说明了:

The system shall not allow the action for the signals SIGKILL or SIGSTOP to be set to SIG_IGN.
....
The system shall not allow a process to catch the signals SIGKILL and SIGSTOP.

如果您检查了 signal() 调用的 return 代码和 errno,您几乎肯定会看到它 failing with EINVAL