This is a creation in Article, where the information may have evolved or changed.
Os/signal packet realization of signal processing
The processing of signal in Golang mainly uses two methods in the Os/signal package: One is the Notify method used to listen to the received signal; One is the stop method used to cancel the listener.
Func Notify (c chan<-os. Signal, sig ... os. Signal)
Func Notify (c chan<-os. Signal, sig ... os. Signal)
The first parameter indicates the channel to receive the signal, and the second and subsequent parameters indicate the signal set to be monitored. If you do not set the signal to listen for all。
Func Main () {c: = Make (chan os. Signal, 0) Signal. Notify (c)//Block until a signal is received. S: = <-c fmt. PRINTLN ("Got signal:", s)//got signal:terminated} result Analysis: Run the program and then kill the corresponding process in the terminal with the KILL command, you will get the result
Func Stop (c chan<-os. Signal)
Func Main () {c: = Make (chan os. Signal, 0) Signal. Notify (c) signal. Stop (c)//Do not allow to continue depositing content into C s: = <-c //c No content, blocked here, so the following statement will not be executed, there is no output fmt. PRINTLN ("Got signal:", s)}
Because the signal is deposited into the channel, the channel feature can be used to make the system or process perform different operations with the select for different signal.