当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。