Skip to content

Instantly share code, notes, and snippets.

@angelbarrera92
Last active December 11, 2020 18:22
Show Gist options
  • Save angelbarrera92/ac38dbbd072b01f2d5c832f7bb6a8ebc to your computer and use it in GitHub Desktop.
Save angelbarrera92/ac38dbbd072b01f2d5c832f7bb6a8ebc to your computer and use it in GitHub Desktop.
capture control-c with confirmation
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
Copy link

ervitis commented Dec 11, 2020

package main

import (
	"bufio"
	"fmt"
	"os"
	"os/signal"
	"strings"
	"sync"
)

func main() {
	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt)

	wg := sync.WaitGroup{}
	wg.Add(1)

	go func() {
		for {
			<-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 text == "yes" {
				wg.Done()
				break
			}
		}
	}()

	wg.Wait()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment