Go project's main goroutine sleep forever?

后端 未结 3 1424
一向
一向 2020-12-08 20:52

Is there any API to let the main goroutine sleep forever?

In other words, I want my project always run except when I stop it.

3条回答
  •  粉色の甜心
    2020-12-08 21:27

    It depends on use cases to choose what kind of sleep you want.

    @icza provides a good and simple solution for literally sleeping forever, but I want to give you some more sweets if you want your system could shutdown gracefully.

    You could do something like this:

    func mainloop() {
        exitSignal := make(chan os.Signal)
        signal.Notify(exitSignal, syscall.SIGINT, syscall.SIGTERM)
        <-exitSignal
    
        systemTeardown()
    }
    

    And in your main:

    func main() {
        systemStart()
        mainloop()
    }
    

    In this way, you could not only ask your main to sleep forever, but you could do some graceful shutdown stuff after your code receives INT or TERM signal from OS, like ctrl+C or kill.

提交回复
热议问题