From d5192456ce26593aadc3e29e43363149639f6cb1 Mon Sep 17 00:00:00 2001 From: akulij Date: Thu, 27 Feb 2025 22:07:30 +0000 Subject: [PATCH] handle sigint --- cmd/age-passgen/main.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/cmd/age-passgen/main.go b/cmd/age-passgen/main.go index 2446bb5..e1a8e22 100644 --- a/cmd/age-passgen/main.go +++ b/cmd/age-passgen/main.go @@ -7,8 +7,10 @@ import ( "io" "log" "os" + "os/signal" "slices" "strconv" + "syscall" "time" "unsafe" @@ -51,6 +53,7 @@ type Flags struct { } func main() { + go setSystemSignalHandlers() flags, err := parseFlags() if err != nil { errorf("error while parsing arguments: %s\n", err) @@ -97,6 +100,30 @@ func main() { } } +func setSystemSignalHandlers() { + go handleSigint() +} + +func handleSigint() { + c := make(chan os.Signal, 1) + signal.Notify(c, os.Interrupt, syscall.SIGTERM) + + state, err := term.GetState(int(os.Stdout.Fd())) + if err != nil { + fmt.Fprint(os.Stderr, "Failed to save state of the terminal") + return + } + + <-c + + err = term.Restore(int(os.Stdout.Fd()), state) + if err != nil { + errorf("Failed to restore state of the terminal") + } + + os.Exit(1) +} + func parseFlags() (*Flags, error) { log.SetFlags(0) flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s", usage) }