// Chapter 39 example: stopping cleanly when you press Ctrl+C. // Run with: go run exercises/39/08-ctrl-c.go // Then press Ctrl+C after a few seconds. package main import ( "context" "fmt" "os" "os/signal" "time" ) func main() { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) defer stop() fmt.Println("Working. Press Ctrl+C to stop.") ticker := time.NewTicker(time.Second) defer ticker.Stop() seconds := 0 for { select { case <-ticker.C: seconds = seconds + 1 fmt.Println("Still working, second", seconds) case <-ctx.Done(): stop() // a second Ctrl+C now ends the program at once fmt.Println("Ctrl+C pressed. Saving and closing...") time.Sleep(500 * time.Millisecond) // pretend to save fmt.Printf("Stopped cleanly after %d seconds.\n", seconds) return } } }