Last active
December 11, 2020 18:22
-
-
Save angelbarrera92/ac38dbbd072b01f2d5c832f7bb6a8ebc to your computer and use it in GitHub Desktop.
capture control-c with confirmation
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 ( | |
"bufio" | |
"fmt" | |
"os" | |
"os/signal" | |
"strings" | |
"syscall" | |
"time" // or "runtime" | |
) | |
func cleanup() { | |
fmt.Println("cleanup") | |
} | |
func main() { | |
c := make(chan os.Signal) | |
signal.Notify(c, os.Interrupt, syscall.SIGTERM) | |
handleSignal(c) | |
for { | |
fmt.Println("sleeping...") | |
time.Sleep(3 * time.Second) // or runtime.Gosched() or similar per @misterbee | |
} | |
} | |
func handleSignal(c chan os.Signal) { | |
go func() { | |
<-c | |
fmt.Println("\r- Ctrl+C pressed in Terminal") | |
fmt.Println("\r- Are you sure you want to stop it? write yes to close it. Press enter to continue") | |
reader := bufio.NewReader(os.Stdin) | |
text, _ := reader.ReadString('\n') | |
text = strings.Replace(text, "\n", "", -1) | |
if strings.Compare("yes", text) == 0 { | |
cleanup() | |
os.Exit(1) | |
} | |
handleSignal(c) | |
}() | |
} |
ervitis
commented
Dec 11, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment