Last active
January 27, 2019 17:55
-
-
Save ajaxray/f6bc96fe6271e3d8c91527839bc025ef to your computer and use it in GitHub Desktop.
Simple go function to prevent exiting program until SIGINT (Ctrl+C) or SIGTERM is received.
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 main | |
import ( | |
"fmt" | |
"os" | |
"os/signal" | |
"syscall" | |
) | |
func main() { | |
fmt.Println("Going to do something great!..") | |
// go func() { | |
// Something you want to be continued | |
// } | |
fmt.Println("(I'll continue doing untill you interrupt 😎 )") | |
waitForSignal() | |
fmt.Println("Exiting program.") | |
} | |
// waitForSignal will prevent exiting the program untill Ctrl+C | |
func waitForSignal() { | |
sigs := make(chan os.Signal, 1) | |
done := make(chan bool, 1) | |
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) | |
go func() { | |
sig := <-sigs | |
fmt.Printf("\nSignal received: ") | |
fmt.Println(sig) | |
done <- true | |
}() | |
<-done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment