说明
本文是个人学习用的非官方中英对照译文,原文: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
killsystem 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
killsystem 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
SIGCHLDsignal 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 SIGSEGVSegmentation fault (e.g., dereferencing a null pointer) SIGINTInterrupt process (e.g., Ctrl-C in terminal window to kill process) SIGCHLDChild process has exited (e.g., a child is now a zombie after running exit)SIGALRMNotify a process a timer goes off (e.g., alarm(2)every 2 secs)SIGKILLTerminate a process (e.g., pkill -9 a.out)SIGBUSBus error occurred (e.g., a misaligned memory address to access an intvalue)SIGSTOPSuspend a process, move to Blocked state (e.g., Ctrl-Z) SIGCONTContinue a blocked process (move it to the Ready state; e.g., bgorfg)
译注
在终端按 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
SIGKILLsignal, the OS will always force the process to exit, and receiving aSIGSTOPsignal 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:
sigactionandsignal. Becausesigactionis POSIX compliant and more featureful, it should be used in production software. However, we usesignalin 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, andSIGCONTsignals using thesignalsystem call (error handling is removed for readability):
1 | /* |
运行时,进程每 5 秒收到一个 SIGALRM(由于 main 和 sigalarm_handler 中对 alarm 的调用)。可以在另一个 shell 中运行 kill 或 pkill 命令来触发 SIGINT 和 SIGCONT 信号。例如,如果进程的 PID 是 1234,可执行文件是 a.out,那么下面的 shell 命令就会向该进程发送 SIGINT 和 SIGCONT 信号,触发它们的信号处理函数运行:
When run, the process receives a
SIGALRMevery 5 seconds (due to the call toalarminmainandsigalarm_handler). TheSIGINTandSIGCONTsignals can be triggered by running thekillorpkillcommands in another shell. For example, if the process’s PID is 1234 and its executable isa.out, then the following shell command sends the processSIGINTandSIGCONTsignals, triggering their signal handler functions to run:
1 | pkill -INT a.out |
编写 SIGCHLD 处理程序
Writing a SIGCHLD handler
回想一下,当一个进程终止时,操作系统会向它的父进程传递一个 SIGCHLD 信号。在创建子进程的程序中,父进程并不总是希望阻塞在 wait 调用上,直到子进程退出。例如,当 shell 程序在后台运行一个命令时,它与子进程并发运行,在子进程于后台运行的同时,继续在前台处理其他 shell 命令。然而,父进程需要调用 wait 来回收退出后的僵尸子进程。否则,僵尸进程永远不会消亡,会一直占用一些系统资源。在这些情况下,父进程可以为 SIGCHLD 信号注册一个信号处理程序。当父进程收到来自已退出子进程的 SIGCHLD 时,它的处理程序代码就会运行,调用 wait 来回收僵尸子进程。
Recall that when a process terminates, the OS delivers a
SIGCHLDsignal to its parent process. In programs that create child processes, the parent process does not always want to block on a call towaituntil 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 callwaitto 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 onSIGCHLDsignals. When the parent receives aSIGCHLDfrom an exited child process, its handler code runs and makes calls towaitto reap its zombie children.
下面是一个代码片段,展示了 SIGCHLD 信号处理函数的实现。这个片段还展示了 main 函数中为 SIGCHLD 信号注册该信号处理函数的部分代码(注意,这应当在任何 fork 调用之前完成):
Below is a code snippet showing the implementation of a signal handler function for
SIGCHLDsignals. This snippet also shows parts of amainfunction that register the signal handler function for theSIGCHLDsignal (note that this should be done before any calls tofork):
1 | /* |
上面的例子把 -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 theWNOHANGflag, which means that the call towaitpiddoes not block if there are no zombie child processes to reap. Also note thatwaitpidis called inside awhileloop 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 callswaitpidin a loop because as it is running, the process could receive additionalSIGCHLDsignals from other exited child process. The OS doesn’t keep track of the number ofSIGCHLDsignals a process receives, it just notes that the process received aSIGCHLDand 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
SIGCHLDsignal, regardless of whether the parent is blocked on a call towaitorwaitpid. If the parent is blocked on a call towaitwhen it receives aSIGCHLD, 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 towait(it just reaped an exited child process). If, however, the parent is blocked on a call towaitpidfor 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 towaitpidif the signal handler code reaped the child for which it was waiting. Otherwise, the parent continues to block on the call towaitpidto wait for the specified child to exit. A call towaitpidwith a PID of a non existent child process (perhaps one that was previously reaped in the signal handler loop) does not block the caller.