第 138 / 187 篇

13.4.1. 信号

说明

本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C13-OS/ipc_signals.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。

13.4.1. Signals

信号(signal)是一个进程通过操作系统发送给另一个进程的软件中断。当一个进程收到信号时,操作系统会中断它当前的执行点,转而运行信号处理程序代码。如果信号处理程序返回,进程就从为处理信号而被中断的地方继续执行。有时信号处理程序会使进程退出,这时它就不会从停下的地方继续执行了。

A signal is a software interrupt that is sent by one process to another process via the OS. When a process receives a signal, its current execution point is interrupted by the OS to run signal handler code. If the signal handler returns, the process’s execution continues from where it was interrupted to handle the signal. Sometimes the signal handler causes the process to exit, and thus it does not continue its execution from where it left off.

信号与硬件中断和陷阱相似,但又与两者都不同。陷阱是进程显式调用系统调用时发生的同步软件中断,而信号是异步的:进程在执行的任何时刻都可能因收到信号而被中断。信号与异步的硬件中断的不同之处在于,信号是由软件而不是硬件设备触发的。

Signals are similar to hardware interrupts and traps but are different from both. Whereas a trap is a synchronous software interrupt that occurs when a process explicitly invokes a system call, signals are asynchronous — a process may be interrupted by the receipt of a signal at any point in its execution. Signals also differ from asynchronous hardware interrupts in that they are triggered by software rather than hardware devices.

一个进程可以通过执行 kill 系统调用向另一个进程发送信号,这个系统调用请求操作系统向另一个进程投递一个信号。操作系统负责把信号投递给目标进程,并设置目标进程的执行状态,使其运行与所投递的特定信号相关联的信号处理程序代码。

A process can send another process a signal by executing the kill system call, which requests that the OS post a signal to another process. The OS handles posting the signal to the target process and setting its execution state to run the signal handler code associated with the particular posted signal.

原书注

kill 系统调用的名字可能会让人误解,而且不幸地带有暴力色彩。尽管它可以(也常常)用来传递终止信号,但它也用来向进程发送其他任何类型的信号。

The name of the kill system call is potentially misleading as well as unfortunately violent. While it can be (and often is) used to deliver a termination signal, it is also used to send any other type of signal to a process.

操作系统自己也用信号来通知进程某些事件。例如,当一个进程的某个子进程退出时,操作系统会向该进程投递一个 SIGCHLD 信号。

The OS itself also uses signals to notify processes of certain events. For example, the OS posts a SIGCHLD signal to a process when one of its child processes exits.

系统定义了固定数量的信号(例如,Linux 定义了 32 种不同的信号)。因此,与消息传递或共享内存等其他进程间通信方法相比,信号提供的进程间通信方式是有限的。

Systems define a fixed number of signals (e.g., Linux defines 32 different signals). As a result, signals provide a limited way in which processes can communicate with one another, as opposed to other interprocess communication methods such as messaging or shared memory.

译注

更准确地说,32 左右指的是 Linux 的「标准信号」(编号 1–31)。按 signal(7) 手册,Linux 内核另外还支持 33 个编号为 32 到 64 的实时信号(real-time signal),程序应使用 SIGRTMIN、SIGRTMAX 宏来引用它们,因为 glibc 的线程实现会占用其中几个。

表 1 列出了一些已定义的信号。更多例子请查看手册页(man 7 signal)。

Table 1 lists some of the defined signals. See the man page (man 7 signal) for additional examples.

表 1. 用于进程间通信的信号示例

Table 1. Example Signals Used for Interprocess Communication

信号名 说明
SIGSEGV 段错误(例如对空指针解引用)
SIGINT 中断进程(例如在终端窗口中按 Ctrl-C 终止进程)
SIGCHLD 子进程已退出(例如子进程运行 exit 后成为僵尸)
SIGALRM 通知进程定时器到时(例如 alarm(2) 每 2 秒一次)
SIGKILL 终止进程(例如 pkill -9 a.out)
SIGBUS 发生总线错误(例如用未对齐的内存地址访问 int 值)
SIGSTOP 挂起进程,使其转入阻塞状态(例如 Ctrl-Z)
SIGCONT 让阻塞的进程继续(使其转入就绪状态;例如 bg 或 fg)
Signal Name Description
SIGSEGV Segmentation fault (e.g., dereferencing a null pointer)
SIGINT Interrupt process (e.g., Ctrl-C in terminal window to kill process)
SIGCHLD Child process has exited (e.g., a child is now a zombie after running exit)
SIGALRM Notify a process a timer goes off (e.g., alarm(2) every 2 secs)
SIGKILL Terminate a process (e.g., pkill -9 a.out)
SIGBUS Bus error occurred (e.g., a misaligned memory address to access an int value)
SIGSTOP Suspend a process, move to Blocked state (e.g., Ctrl-Z)
SIGCONT Continue a blocked process (move it to the Ready state; e.g., bg or fg)

译注

在终端按 Ctrl-Z 发送的其实是 SIGTSTP(「在终端键入的停止」),而不是 SIGSTOP。两者的默认动作都是停止进程,区别在于 SIGTSTP 可以被程序捕获或忽略,而 SIGSTOP 和 SIGKILL 一样不能被捕获、阻塞或忽略(见 signal(7))。

当进程收到一个信号时,可能发生下面几种默认动作之一:

When a process receives a signal, one of several default actions can occur:

  • 进程终止
  • the process can terminate
  • 信号被忽略
  • the signal can be ignored
  • 进程被阻塞
  • the process can be blocked
  • 进程被解除阻塞
  • the process can be unblocked

操作系统为每个信号编号定义了默认动作,并提供默认的信号处理程序代码。不过,应用程序员可以改变大多数信号的默认动作,并编写自己的信号处理程序代码。如果应用程序没有为某个信号注册自己的信号处理函数,那么进程收到该信号时,就执行操作系统的默认处理程序。对于某些信号,操作系统定义的默认动作不能被应用程序的信号处理程序代码覆盖。例如,如果进程收到 SIGKILL 信号,操作系统总会强制进程退出;收到 SIGSTOP 信号总会使进程阻塞,直到它收到让它继续(SIGCONT)或退出(SIGKILL)的信号。

The OS defines a default action and supplies the default signal handler code for every signal number. Application programmers, however, can change the default action of most signals and can write their own signal handler code. If an application program doesn’t register its own signal handler function for a particular signal, then the OS’s default handler executes when the process receives a signal. For some signals, the OS-defined default action cannot be overridden by application signal handler code. For example, if a process receives a SIGKILL signal, the OS will always force the process to exit, and receiving a SIGSTOP signal will always block the process until it receives a signal to continue (SIGCONT) or to exit (SIGKILL).

Linux 支持两个不同的系统调用,可以用来改变信号的默认行为,或者为某个特定信号注册信号处理程序:sigaction 和 signal。由于 sigaction 符合 POSIX 标准且功能更丰富,在正式的软件中应当使用它。不过,我们在示例代码中使用 signal,因为它更容易理解。

Linux supports two different system calls that can be used to change the default behavior of a signal or to register a signal handler on a particular signal: sigaction and signal. Because sigaction is POSIX compliant and more featureful, it should be used in production software. However, we use signal in our example code because it is easier to understand.

下面是一个示例程序,它用 signal 系统调用为 SIGALRM、SIGINT 和 SIGCONT 信号注册信号处理程序(为了可读性去掉了错误处理):

Following is an example program that registers signal handlers for SIGALRM, SIGINT, and SIGCONT signals using the signal system call (error handling is removed for readability):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
* Example of signal handlers for SIGALRM, SIGINT, and SIGCONT
*
* A signal handler function prototype must match:
* void handler_function_name(int signum);
*
* Compile and run this program, then send this process signals by executing:
* kill -INT pid (or Ctrl-C) will send a SIGINT
* kill -CONT pid (or Ctrl-Z fg) will send a SIGCONT
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

/* signal handler for SIGALRM */
void sigalarm_handler(int sig) {
printf("BEEP, signal number %d\n.", sig);
fflush(stdout);
alarm(5); /* sends another SIGALRM in 5 seconds */
}

/* signal handler for SIGCONT */
void sigcont_handler(int sig) {
printf("in sigcont handler function, signal number %d\n.", sig);
fflush(stdout);
}

/* signal handler for SIGINT */
void sigint_handler(int sig) {
printf("in sigint handler function, signal number %d...exiting\n.", sig);
fflush(stdout);
exit(0);
}

/* main: register signal handlers and repeatedly block until receive signal */
int main(void) {

/* Register signal handlers. */
if (signal(SIGCONT, sigcont_handler) == SIG_ERR) {
printf("Error call to signal, SIGCONT\n");
exit(1);
}

if (signal(SIGINT, sigint_handler) == SIG_ERR) {
printf("Error call to signal, SIGINT\n");
exit(1);
}

if (signal(SIGALRM, sigalarm_handler) == SIG_ERR) {
printf("Error call to signal, SIGALRM\n");
exit(1);
}

printf("kill -CONT %d to send SIGCONT\n", getpid());

alarm(5); /* sends a SIGALRM in 5 seconds */

while(1) {
pause(); /* wait for a signal to happen */
}
}

运行时,进程每 5 秒收到一个 SIGALRM(由于 main 和 sigalarm_handler 中对 alarm 的调用)。可以在另一个 shell 中运行 kill 或 pkill 命令来触发 SIGINT 和 SIGCONT 信号。例如,如果进程的 PID 是 1234,可执行文件是 a.out,那么下面的 shell 命令就会向该进程发送 SIGINT 和 SIGCONT 信号,触发它们的信号处理函数运行:

When run, the process receives a SIGALRM every 5 seconds (due to the call to alarm in main and sigalarm_handler). The SIGINT and SIGCONT signals can be triggered by running the kill or pkill commands in another shell. For example, if the process’s PID is 1234 and its executable is a.out, then the following shell command sends the process SIGINT and SIGCONT signals, triggering their signal handler functions to run:

1
2
3
4
5
pkill -INT a.out
kill -INT 1234

pkill -CONT a.out
kill -CONT 1234

编写 SIGCHLD 处理程序

Writing a SIGCHLD handler

回想一下,当一个进程终止时,操作系统会向它的父进程传递一个 SIGCHLD 信号。在创建子进程的程序中,父进程并不总是希望阻塞在 wait 调用上,直到子进程退出。例如,当 shell 程序在后台运行一个命令时,它与子进程并发运行,在子进程于后台运行的同时,继续在前台处理其他 shell 命令。然而,父进程需要调用 wait 来回收退出后的僵尸子进程。否则,僵尸进程永远不会消亡,会一直占用一些系统资源。在这些情况下,父进程可以为 SIGCHLD 信号注册一个信号处理程序。当父进程收到来自已退出子进程的 SIGCHLD 时,它的处理程序代码就会运行,调用 wait 来回收僵尸子进程。

Recall that when a process terminates, the OS delivers a SIGCHLD signal to its parent process. In programs that create child processes, the parent process does not always want to block on a call to wait until its child processes exit. For example, when a shell program runs a command in the background, it continues to run concurrently with its child process, handling other shell commands in the foreground as the child process runs in the background. A parent process, however, needs to call wait to reap its zombie child processes after they exit. If not, the zombie processes will never die and will continue to hold on to some system resources. In these cases, the parent process can register a signal handler on SIGCHLD signals. When the parent receives a SIGCHLD from an exited child process, its handler code runs and makes calls to wait to reap its zombie children.

下面是一个代码片段,展示了 SIGCHLD 信号处理函数的实现。这个片段还展示了 main 函数中为 SIGCHLD 信号注册该信号处理函数的部分代码(注意,这应当在任何 fork 调用之前完成):

Below is a code snippet showing the implementation of a signal handler function for SIGCHLD signals. This snippet also shows parts of a main function that register the signal handler function for the SIGCHLD signal (note that this should be done before any calls to fork):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
* signal handler for SIGCHLD: reaps zombie children
* signum: the number of the signal (will be 20 for SIGCHLD)
*/
void sigchld_handler(int signum) {
int status;
pid_t pid;

/*
* reap any and all exited child processes
* (loop because there could be more than one)
*/
while( (pid = waitpid(-1, &status, WNOHANG)) > 0) {
/* uncomment debug print stmt to see what is being handled
printf("signal %d me:%d child: %d\n", signum, getpid(), pid);
*/
}
}

int main(void) {

/* register SIGCHLD handler: */
if ( signal(SIGCHLD, sigchld_handler) == SIG_ERR) {
printf("ERROR signal failed\n");
exit(1);
}

...

/* create a child process */
pid = fork();
if(pid == 0) {
/* child code...maybe call execvp */
...
}
/* the parent continues executing concurrently with child */
...

上面的例子把 -1 作为 PID 传给 waitpid,意思是「回收任何一个僵尸子进程」。它还传入了 WNOHANG 标志,表示如果没有可回收的僵尸子进程,waitpid 调用不会阻塞。还要注意,waitpid 是在一个 while 循环中调用的,只要它返回有效的 PID 值(只要它回收了一个僵尸子进程),循环就继续。信号处理函数在循环中调用 waitpid 是很重要的,因为在它运行期间,进程可能会收到来自其他已退出子进程的更多 SIGCHLD 信号。操作系统并不记录进程收到了多少个 SIGCHLD 信号,它只记下进程收到过 SIGCHLD,并中断其执行去运行处理程序代码。因此,如果没有这个循环,信号处理程序可能会漏掉一些僵尸子进程而没有回收。

The example above passes -1 as the PID to waitpid, which means “reap any zombie child process.” It also passes the WNOHANG flag, which means that the call to waitpid does not block if there are no zombie child processes to reap. Also note that waitpid is called inside a while loop that continues as long as it returns a valid PID value (as long as it reaps a zombie child process). It is important that the signal handler function calls waitpid in a loop because as it is running, the process could receive additional SIGCHLD signals from other exited child process. The OS doesn’t keep track of the number of SIGCHLD signals a process receives, it just notes that the process received a SIGCHLD and interrupts its execution to run the handler code. As a result, without the loop, the signal handler could miss reaping some zombie children.

无论父进程是否阻塞在 wait 或 waitpid 调用上,只要父进程收到 SIGCHLD 信号,信号处理程序就会执行。如果父进程在收到 SIGCHLD 时阻塞在 wait 调用上,它会被唤醒并运行信号处理程序代码,回收一个或多个僵尸子进程。然后,它从程序中 wait 调用之后的地方继续执行(它刚刚回收了一个已退出的子进程)。然而,如果父进程阻塞在针对某个特定子进程的 waitpid 调用上,那么在它的信号处理程序代码回收了一个已退出的子进程之后,父进程可能继续阻塞,也可能不再阻塞。如果信号处理程序代码回收的正是父进程在等待的那个子进程,父进程就从 waitpid 调用之后继续执行。否则,父进程会继续阻塞在 waitpid 调用上,等待指定的子进程退出。用一个不存在的子进程(也许是之前已在信号处理程序的循环中被回收的子进程)的 PID 调用 waitpid,不会使调用者阻塞。

The signal handler executes whenever the parent receives a SIGCHLD signal, regardless of whether the parent is blocked on a call to wait or waitpid. If the parent is blocked on a call to wait when it receives a SIGCHLD, it wakes up and runs the signal handler code to reap one or more of its zombie children. It then continues execution at the point in the program after the call to wait (it just reaped an exited child process). If, however, the parent is blocked on a call to waitpid for a specific child, then the parent may or may not continue to block after its signal handler code runs to reap an exited child. The parent process continues execution after its call to waitpid if the signal handler code reaped the child for which it was waiting. Otherwise, the parent continues to block on the call to waitpid to wait for the specified child to exit. A call to waitpid with a PID of a non existent child process (perhaps one that was previously reaped in the signal handler loop) does not block the caller.