Home >Backend Development >Golang >How to exit the process in golang?

How to exit the process in golang?

coldplay.xixi
coldplay.xixiOriginal
2020-07-18 15:10:107085browse

Golang's method of exiting the process: first define a [chan struct{}]; then call the [close()] function to close the channel and pass the exit signal to each goroutine; finally get [<-chan ], just exit the break loop.

How to exit the process in golang?

Golang's method of exiting the process:

The following is a solution for the main function to exit func, production environment Here, exit func may perform a lot of closing operations, and the closing objects are likely to be many goroutines with embedded infinite loops. How to pass the exit signal to each goroutine?

My usual approach is to define a chan struct{} . When the close() function is called to close the channel, all <-chanThe operations will be performed at the same time, so that the exit signal is passed to each goroutine, and each goroutine can be polled through select (by default, select under Linux calls epoll for polling). When is obtained <-chan, break loop

package main
import(
        "fmt"
        "os"
        "os/signal"
        "syscall"
)
func main(){
        signalChan := make(chan os.Signal,1) //创建一个信号量的chan,缓存为1,(0,1)意义不大
        signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)//让进城收集信号量。
        fmt.Println("i am workding!")
        <-signalChan         
        ExitFunc()
}
func ExitFunc(){
        fmt.Println("i am exiting!")
}

Related learning recommendations: Go language tutorial

The above is the detailed content of How to exit the process in golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn