This is a creation in Article, where the information may have evolved or changed.
First look at a simple example of signal processing
Package MainImport ("FMT""OS""Os/signal")func Main() {C := Make(Chan OS.Signal, 1) # Watch ThisSignal.Notify(C, OS.Interrupt)s := <-CFMT.Println("Got signal:", s)}
The length of the channel,channel that holds the signal object is first created at 1.
It then uses notify to register the signal processing, associating the interrupt signal with the channel.
The process hangs there until it receives a CTRL + C trigger interrupt signal, the channel will be plugged into a signal object, <-C will return, print the Signal object and then exit the program.
The above example is a simple example of signal processing provided in the official documentation.
It is worth noting that the channel here is a non-blocking channel with a length of 1. Can it be a non-blocking channel, can it be an n-length blocking channel?
Let's take a look at what the official documents say.
The word relay in the document is very interesting, its English is conveyed, broadcast, a bit like the meaning of collecting.
Notify will make the parameter C[channel] to collect the input signal. If the signal parameter sig is not provided, all types of signals will be collected. Otherwise only the signal type provided in the collection parameters.
Signal collection is non-blocking, what does it mean?
If the channel is full, the signal being collected will be discarded because there is no space to accommodate it. The process of collecting is equivalent to
select{ casec<-sig: default:}
If the channel length is 1, when a series of signals arrive at the same time, only the first signal will be collected, if the channel consumer is not available to deal with.
If the channel length is 0, the signal may be lost. For example, the following code
Package MainImport ("FMT""OS""Os/signal" "Time")func Main() {C := Make(Chan OS.Signal, 1)Signal.Notify(C, OS.Interrupt) Time.Sleep(5 * Time.Second)s := <-CFMT.Println("Got signal:", s)}
We in the program sleep when the crazy press CTRL + C for 2 seconds, and then wait until the end of 5 Seconds of sleep, you will find that the program is still hanging there, will not exit, then need to press CTRL + C to exit.
Read more articles about the "code hole" of the column