Last active
August 7, 2019 06:25
-
-
Save instabledesign/494ffc8bafd5781bb4d43dbe2111cc30 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package signal | |
import ( | |
"os" | |
"os/signal" | |
) | |
// This is a really small signal subscriber | |
// Signal subscriber that allows you to attach a callback to an `os.Signal` notification. | |
// Usefull to react to any os.Signal. | |
// It returns an `unsubscribe` function that stops the goroutine and clean allocated object | |
// | |
// Example: | |
// unsubscriber := signal.subscribe(func(s os.Signal) { | |
// fmt.Println("process as been asked to be stopped") | |
// }, os.SIGSTOP) | |
// | |
// call "unsubscriber()" in order to detach your callback and clean memory | |
// | |
// /!\ CAUTION /!\ | |
// If you call it with second arg to `nil`, no signal will be listened | |
// signal.subscribe(func(s os.Signal) {fmt.Println("NEVER BE CALLED")}, nil) | |
func Subscribe(callback func(os.Signal), signals ...os.Signal) func() { | |
signalChan := make(chan os.Signal, 1) | |
stopChan := make(chan bool, 1) | |
signal.Notify(signalChan, signals...) | |
go func() { | |
for { | |
select { | |
case <-stopChan: | |
signal.Stop(signalChan) | |
close(stopChan) | |
close(signalChan) | |
return | |
case sig := <-signalChan: | |
callback(sig) | |
} | |
} | |
}() | |
return func() { | |
stopChan <- true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Move to package https://github.com/gol4ng/signal