Golang catch signals

后端 未结 2 828
南笙
南笙 2021-02-01 03:54

I want to implement a \"process wrapper\" in Go. Basically what it will do, is launch a process (lets say a node server) and monitor it (catch signals like SIGKILL, SIGTERM ...)

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-01 04:10

    You can use signal.Notify :

    import (
    "os"
    "os/signal"
    "syscall"
    )
    
    func main() {
        signalChannel := make(chan os.Signal, 2)
        signal.Notify(signalChannel, os.Interrupt, syscall.SIGTERM)
        go func() {
            sig := <-signalChannel
            switch sig {
            case os.Interrupt:
                //handle SIGINT
            case syscall.SIGTERM:
                //handle SIGTERM
            }
        }()
        // ...
    }
    

提交回复
热议问题