Go语言-信号os.Interrupt和信号syscall.SIGTERM的应用

实例

package main

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

func worker(stop <-chan bool) {
    for {
        select {
            case <-stop:
                fmt.Println("exit")
                return
            default:
                fmt.Println("running...")
                time.Sleep(3)
        }
    }
}

func main() {
    stop := make(chan bool)
    var wg sync.WaitGroup
    for i := 0; i < 3; i++ {
        wg.Add(1)
        go func(stop <-chan bool) {
            defer wg.Done()
          worker(stop)
        }(stop)
    }
    waitForSignal()
    close(stop)
    fmt.Println("stopping all job")
    wg.Wait()
}

func waitForSignal() {
    sigs := make(chan os.Signal)
    signal.Notify(sigs, os.Interrupt)
    signal.Notify(sigs, syscall.SIGTERM)
    fmt.Println(<-sigs)
}

运行结果

pkill信号syscall.SIGTERM

    ...
    running...
    running...
    running...
    running...
    terminated
    running...
    running...
    stopping all job
    exit
    exit
    exit

或者ctrl+c信号os.Interrupt

running...
interrupt
stopping all job
running...
exit
exit
exit

转载于:https://blog.51cto.com/12880687/2130282

你可能感兴趣的:(Go语言-信号os.Interrupt和信号syscall.SIGTERM的应用)