當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO Notify用法及代碼示例

GO語言"os/signal"包中"Notify"函數的用法及代碼示例。

用法:

func Notify(c chan<- os.Signal, sig ...os.Signal)

通知使包信號將傳入信號中繼到 c。如果沒有提供信號,所有傳入的信號將被中繼到 c。否則,隻有提供的信號會。

包信號不會阻塞發送到 c:調用者必須確保 c 有足夠的緩衝區空間來跟上預期的信號速率。對於僅用於通知一個信號值的通道,大小為 1 的緩衝區就足夠了。

允許使用同一通道多次調用 Notify:每次調用都會擴展發送到該通道的信號集。從集合中移除信號的唯一方法是調用 Stop。

允許使用不同的通道和相同的信號多次調用 Notify:每個通道獨立接收傳入信號的副本。

例子:

package main

import (
    "fmt"
    "os"
    "os/signal"
)

func main() {
    // Set up channel on which to send signal notifications.
    // We must use a buffered channel or risk missing the signal
    // if we're not ready to receive when the signal is sent.
    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt)

    // Block until a signal is received.
    s := <-c
    fmt.Println("Got signal:", s)
}

示例(所有信號):

package main

import (
    "fmt"
    "os"
    "os/signal"
)

func main() {
    // Set up channel on which to send signal notifications.
    // We must use a buffered channel or risk missing the signal
    // if we're not ready to receive when the signal is sent.
    c := make(chan os.Signal, 1)

    // Passing no signals to Notify means that
    // all signals will be sent to the channel.
    signal.Notify(c)

    // Block until any signal is received.
    s := <-c
    fmt.Println("Got signal:", s)
}

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Notify。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。