golang捕获ctrl+c退出程序

在golang当中如何捕获ctrl+c命令,让程序有序的的退出?

首先测试一段golang代码,捕获SIGINT和SIGKILL

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, os.Kill)

s := <-c
fmt.Println("Got signal:", s)

在多goroutines当中如何退出?我们假设有一个生产者,一个消费者,这个时候应该让生产者去捕获消息,关闭channel,生产者退出;消费者感知到channel关闭,消费者退出。

package main

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

var c chan os.Signal
var msgQueue chan *string
var wg sync.WaitGroup

func Producer(){
    i := 0
    LOOP:
    for{
        select {
        case s := <-c:
            fmt.Println()
            fmt.Println("Producer | get", s)
            break LOOP
        default:
        }

        i ++
        s := fmt.Sprintf("work-%d", i)
        fmt.Println("Producer | produce", s)
        msgQueue <- &s
        time.Sleep(500 * time.Millisecond)
    }

    close(msgQueue)
    fmt.Println("Producer | close channel, exit")
    wg.Done()
}

func Consumer(){
    for m := range msgQueue{
        if m != nil{
            fmt.Println("Consumer | consume", *m)
        }else{
            fmt.Println("Consumer | channel closed")
            break
        }
    }
    fmt.Println("Consumer | exit")
    wg.Done()
}

func main(){
    c = make(chan os.Signal, 1)
    msgQueue = make(chan *string, 1000)
    signal.Notify(c, os.Interrupt, os.Kill)

    //pruducer
    wg.Add(1)
    go Producer()

    //consumer
    wg.Add(1)
    go Consumer()

    wg.Wait()
}

运行结果:

Producer | produce work-1
Consumer | consume work-1
Producer | produce work-2
Consumer | consume work-2
Producer | produce work-3
Consumer | consume work-3
Producer | produce work-4
Consumer | consume work-4

Producer | get interrupt
Producer | close channel, exit
Consumer | exit

参考:
1. http://www.oschina.net/translate/golang-graceful-stop?lang=eng

你可能感兴趣的:(golang)