Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go信号实例
Go信号实例
作者:--    发布时间:2019-11-20

有时我们希望go程序能够智能地处理unix信号。 例如,可能希望服务器在接收到sigterm时正常关闭,或者在收到sigint时使用命令行工具停止处理输入。下面介绍如何使用go语言处理信号。

go信号通知通过在通道上发送os.signal值来工作。创建一个通道来接收这些通知(还会在程序退出时通知我们)。

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html

signal.go的完整代码如下所示 -

package main

import "fmt"
import "os"
import "os/signal"
import "syscall"

func main() {

    // 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(chan os.signal, 1)
    done := make(chan bool, 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.
    go func() {
        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")
}

执行上面代码,将得到以下输出结果 -

f:\worksp\golang>go run signal.go
awaiting signal
[ctl+c]
interrupt
exiting

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册