信號類型
個平台的信號定義或許有些不同。下面列出了POSIX中定義的信號。
Linux 使用34-64信號用作實時系統中。
命令 man 7 signal 提供了官方的信號介紹。
在POSIX.1-1990標准中定義的信號列表
| 信號 | 值 | 動作 | 說明 |
|---|---|---|---|
| SIGHUP | 1 | Term | 終端控制進程結束(終端連接斷開) |
| SIGINT | 2 | Term | 用戶發送INTR字符(Ctrl+C)觸發 |
| SIGQUIT | 3 | Core | 用戶發送QUIT字符(Ctrl+/)觸發 |
| SIGILL | 4 | Core | 非法指令(程序錯誤、試圖執行數據段、棧溢出等) |
| SIGABRT | 6 | Core | 調用abort函數觸發 |
| SIGFPE | 8 | Core | 算術運行錯誤(浮點運算錯誤、除數為零等) |
| SIGKILL | 9 | Term | 無條件結束程序(不能被捕獲、阻塞或忽略) |
| SIGSEGV | 11 | Core | 無效內存引用(試圖訪問不屬於自己的內存空間、對只讀內存空間進行寫操作) |
| SIGPIPE | 13 | Term | 消息管道損壞(FIFO/Socket通信時,管道未打開而進行寫操作) |
| SIGALRM | 14 | Term | 時鍾定時信號 |
| SIGTERM | 15 | Term | 結束程序(可以被捕獲、阻塞或忽略) |
| SIGUSR1 | 30,10,16 | Term | 用戶保留 |
| SIGUSR2 | 31,12,17 | Term | 用戶保留 |
| SIGCHLD | 20,17,18 | Ign | 子進程結束(由父進程接收) |
| SIGCONT | 19,18,25 | Cont | 繼續執行已經停止的進程(不能被阻塞) |
| SIGSTOP | 17,19,23 | Stop | 停止進程(不能被捕獲、阻塞或忽略) |
| SIGTSTP | 18,20,24 | Stop | 停止進程(可以被捕獲、阻塞或忽略) |
| SIGTTIN | 21,21,26 | Stop | 后台程序從終端中讀取數據時觸發 |
| SIGTTOU | 22,22,27 | Stop | 后台程序向終端中寫數據時觸發 |
在SUSv2和POSIX.1-2001標准中的信號列表:
| 信號 | 值 | 動作 | 說明 |
|---|---|---|---|
| SIGTRAP | 5 | Core | Trap指令觸發(如斷點,在調試器中使用) |
| SIGBUS | 0,7,10 | Core | 非法地址(內存地址對齊錯誤) |
| SIGPOLL | Term | Pollable event (Sys V). Synonym for SIGIO | |
| SIGPROF | 27,27,29 | Term | 性能時鍾信號(包含系統調用時間和進程占用CPU的時間) |
| SIGSYS | 12,31,12 | Core | 無效的系統調用(SVr4) |
| SIGURG | 16,23,21 | Ign | 有緊急數據到達Socket(4.2BSD) |
| SIGVTALRM | 26,26,28 | Term | 虛擬時鍾信號(進程占用CPU的時間)(4.2BSD) |
| SIGXCPU | 24,24,30 | Core | 超過CPU時間資源限制(4.2BSD) |
| SIGXFSZ | 25,25,31 | Core | 超過文件大小資源限制(4.2BSD) |
Go中的Signal發送和處理
有時候我們想在Go程序中處理Signal信號,比如收到 SIGTERM 信號后優雅的關閉程序(參看下一節的應用)。
Go信號通知機制可以通過往一個channel中發送 os.Signal 實現。
首先我們創建一個os.Signal channel,然后使用 signal.Notify 注冊要接收的信號。
packagemain
import"fmt"
import"os"
import"os/signal"
import"syscall"
funcmain() {
// Go signal notification works by sending `os.Signal`
// values on a channel. We'll create a channel to
// receive these notifications (we'll also make one to
// notify us when the program can exit).
sigs := make(chanos.Signal,1)
done := make(chanbool,1)
// `signal.Notify` registers the given channel to
// receive notifications of the specified signals.
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
// This goroutine executes a blocking receive for
// signals. When it gets one it'll print it out
// and then notify the program that it can finish.
gofunc() {
sig := <-sigs
fmt.Println()
fmt.Println(sig)
done <- true
}()
// The program will wait here until it gets the
// expected signal (as indicated by the goroutine
// above sending a value on `done`) and then exit.
fmt.Println("awaiting signal")
<-done
fmt.Println("exiting")
}
go run main.go 執行這個程序,敲入ctrl-C會發送 SIGINT 信號。 此程序接收到這個信號后會打印退出。
