GO語言"os/signal"包中"NotifyContext"函數的用法及代碼示例。
用法:
func NotifyContext(parent context.Context, signals ...os.Signal)(ctx context.Context, stop context.CancelFunc)
NotifyContext 當列出的信號之一到達、調用返回的停止函數或父上下文的 Done 通道關閉時(以先發生者為準),返回標記為完成的父上下文的副本(其 Done 通道已關閉) .
stop 函數取消注冊信號行為,就像 signal.Reset 一樣,可以恢複給定信號的默認行為。例如,接收 os.Interrupt 的 Go 程序的默認行為是退出。調用 NotifyContext(parent, os.Interrupt) 將改變行為以取消返回的上下文。在調用返回的停止函數之前,接收到的未來中斷不會觸發默認(退出)行為。
stop 函數釋放與其關聯的資源,因此代碼應該在此上下文中運行的操作完成後立即調用 stop,並且不再需要將信號轉移到上下文中。
例子:
這個例子傳遞一個帶有信號的上下文來告訴阻塞函數它應該在收到信號後放棄它的工作。
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"time"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
p, err := os.FindProcess(os.Getpid())
if err != nil {
log.Fatal(err)
}
// On a Unix-like system, pressing Ctrl+C on a keyboard sends a
// SIGINT signal to the process of the program in execution.
//
// This example simulates that by sending a SIGINT signal to itself.
if err := p.Signal(os.Interrupt); err != nil {
log.Fatal(err)
}
select {
case <-time.After(time.Second):
fmt.Println("missed signal")
case <-ctx.Done():
fmt.Println(ctx.Err()) // prints "context canceled"
stop() // stop receiving signal notifications as soon as possible.
}
}
輸出:
context canceled
相關用法
- GO Notify用法及代碼示例
- GO NotFoundHandler用法及代碼示例
- GO Node用法及代碼示例
- GO NewFromFiles用法及代碼示例
- GO NumError用法及代碼示例
- GO NewReader用法及代碼示例
- GO NewCBCDecrypter用法及代碼示例
- GO NewCFBDecrypter用法及代碼示例
- GO NewCFBEncrypter用法及代碼示例
- GO NewReplacer用法及代碼示例
- GO New用法及代碼示例
- GO NewGCM用法及代碼示例
- GO NewTripleDESCipher用法及代碼示例
- GO NewWriter用法及代碼示例
- GO NewCBCEncrypter用法及代碼示例
- GO NewOFB用法及代碼示例
- GO NewTLSServer用法及代碼示例
- GO NewTicker用法及代碼示例
- GO NewCTR用法及代碼示例
- GO NewEncoder用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 NotifyContext。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。