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

How to exit the process in golang?

coldplay.xixi
Release: 2020-07-18 15:10:10
Original
7058 people have browsed it

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!")
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template