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.