個平臺的信號定義或許有些不一樣。下面列出了POSIX中定義的信號。函數
Linux 使用34-64信號用做實時系統中。性能
命令 man 7 signal
提供了官方的信號介紹。ui
在POSIX.1-1990標準中定義的信號列表spa
信號 | 值 | 動做 | 說明 |
---|---|---|---|
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信號,好比收到 SIGTERM
信號後優雅的關閉程序(參看下一節的應用)。code
Go信號通知機制能夠經過往一個channel中發送 os.Signal
實現。blog
首先咱們建立一個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") }
執行這個程序,敲入ctrl-C會發送 信號。 此程序接收到這個信號後會打印退出。go run main.goSIGINT