1. 程式人生 > >golang捕獲ctrl+c退出程式

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