Golang how to gracefully handle exit

Source: Internet
Author: User
Tags sigint signal
This is a creation in Article, where the information may have evolved or changed. Sometimes we want to process signal signals in the GO program, such as gracefully closing a program after receiving a sigterm signal (see the application in the next section).
The GO signal notification mechanism can be implemented by sending os.signal to a channel.

First we create an OS. Signal channel, then use Signal. Notify register to receive the signal.

Package Mainimport "FMT" import "OS" import "os/signal" import "Syscall" Func Main () {//GO signal notification works by S Ending ' OS. Signal '//values on a channel. We'll create a channel to//receive these notifications (we'll also make one to//notify us if the program can E    XIT). SIGs: = Make (chan os. Signal, 1) Done: = Make (chan bool, 1)//' Signal.    Notify ' registers the given channel to//receive notifications of the specified signals. Signal. Notify (SIGs, Syscall. SIGINT, Syscall. SIGTERM)//This goroutine executes a blocking receive for//signals.    When it gets one it's ll print it out//and then notify the program that it can finish. Go func () {sig: = <-sigs FMT. Println () fmt. Println (SIG) Done <-True} ()//The program would wait here until it gets the//expected signal (as in    Dicated by the Goroutine//above sending a value of "done") and then exit. Fmt. PRINTLN ("Awaiting signal") <-done    Fmt. Println ("Exiting")}


Go run Main.go executes this program, and typing CTRL-C sends a SIGINT signal. This program will print out after receiving this signal.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.