Linux 中信号有点类似与硬件中的中断,提供了一种处理异步事件的方法。应用程序并不需要特意的去配置就可以接收信号并作出默认的行为,当然应用程序也可以忽略或者注册回调函数来处理特定信号。
1. 产生
信号可以由内核、程序自身或者其他程序来生成
- 用户在终端输入 CTRL + C就可以给应用程序发送一个SIGINT信号。
- 程序中一个数除以0,内核会产生一个 SIGFPE信号
- 程序非法访问了一段内存会由内核产生一个 SIGBUS信号
- 使用 kill可以向其他线程发送特定的信号
- 使用 raise可以向自身发送特定的信号
- supervisor在执行 stop 之后会给程序发送一个- SIGTERM信号
2. 信号行为
信号的默认行为有五种,分别为
- 
Terminate 默认会结束程序 
- 
Ignore 默认会忽略该信号 
- 
Core 接收程序并生成 core dump 文件 
- 
Continue 继续执行程序 
- 
Stop 停止执行程序 
3. 信号的屏蔽与捕获
应用可以根据自身的业务需要对特定的信号进行屏蔽或者捕获,不过需要注意的是 SIGKILL 与 SIGSTOP 是不可以被屏蔽以及捕获的。
#include <signal.h>
#include <stdio.h>
 
int main(void)
{
    /* ignoring the signal */
    signal(SIGTERM, SIG_IGN);
    raise(SIGTERM);
    printf("Exit main()\n");
}
如果需要忽略特定信号只需要将对应的信号处理函数设置为 SIG_IGN 宏即可
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void sigHandler(int sig)
{
    if(sig == SIGTERM)
    {
        printf("SIGTERM\n");
    }
}
int main()
{
    signal(SIGTERM, sigHandler);
    raise(SIGTERM);
    return 0;
}
如果应用需要收到信号后执行对应的操作可以写一个自定义的信号处理函数
4. Use Case
- 通过信号强行结束一个程序,可以使用 kill -9 <PID>
- 在程序运行异常但是没有挂掉的情况下可以使用 kill -3 <PID>来生成 core dump。
5. 信号表
| Signal | Portable number | Default action | Description | 
|---|---|---|---|
| SIGABRT | 6 | Terminate (core dump) | Process abort signal | 
| SIGALRM | 14 | Terminate | Alarm clock | 
| SIGBUS | — | Terminate (core dump) | Access to an undefined portion of a memory object | 
| SIGCHLD | — | Ignore | Child process terminated, stopped, or continued | 
| SIGCONT | — | Continue | Continue executing, if stopped | 
| SIGFPE | 8 | Terminate (core dump) | Erroneous arithmetic operation | 
| SIGHUP | 1 | Terminate | Hangup | 
| SIGILL | 4 | Terminate (core dump) | Illegal instruction | 
| SIGINT | 2 | Terminate | Terminal interrupt signal | 
| SIGKILL | 9 | Terminate | Kill (cannot be caught or ignored) | 
| SIGPIPE | 13 | Terminate | Write on a pipe with no one to read it | 
| SIGPOLL | — | Terminate | Pollable event | 
| SIGPROF | — | Terminate | Profiling timer expired | 
| SIGQUIT | 3 | Terminate (core dump) | Terminal quit signal | 
| SIGSEGV | 11 | Terminate (core dump) | Invalid memory reference | 
| SIGSTOP | — | Stop | Stop executing (cannot be caught or ignored) | 
| SIGSYS | — | Terminate (core dump) | Bad system call | 
| SIGTERM | 15 | Terminate | Termination signal | 
| SIGTRAP | 5 | Terminate (core dump) | Trace/breakpoint trap | 
| SIGTSTP | — | Stop | Terminal stop signal | 
| SIGTTIN | — | Stop | Background process attempting read | 
| SIGTTOU | — | Stop | Background process attempting write | 
| SIGUSR1 | — | Terminate | User-defined signal 1 | 
| SIGUSR2 | — | Terminate | User-defined signal 2 | 
| SIGURG | — | Ignore | Out-of-band data is available at a socket | 
| SIGVTALRM | — | Terminate | Virtual timer expired | 
| SIGXCPU | — | Terminate (core dump) | CPU time limit exceeded | 
| SIGXFSZ | — | Terminate (core dump) | File size limit exceeded | 
| SIGWINCH | — | Ignore | Terminal window size changed | 
