github.com/AndrienkoAleksandr/go@v0.0.19/src/os/signal/example_unix_test.go (about) 1 // Copyright 2020 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 //go:build unix 6 7 package signal_test 8 9 import ( 10 "context" 11 "fmt" 12 "log" 13 "os" 14 "os/signal" 15 "time" 16 ) 17 18 // This example passes a context with a signal to tell a blocking function that 19 // it should abandon its work after a signal is received. 20 func ExampleNotifyContext() { 21 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) 22 defer stop() 23 24 p, err := os.FindProcess(os.Getpid()) 25 if err != nil { 26 log.Fatal(err) 27 } 28 29 // On a Unix-like system, pressing Ctrl+C on a keyboard sends a 30 // SIGINT signal to the process of the program in execution. 31 // 32 // This example simulates that by sending a SIGINT signal to itself. 33 if err := p.Signal(os.Interrupt); err != nil { 34 log.Fatal(err) 35 } 36 37 select { 38 case <-time.After(time.Second): 39 fmt.Println("missed signal") 40 case <-ctx.Done(): 41 fmt.Println(ctx.Err()) // prints "context canceled" 42 stop() // stop receiving signal notifications as soon as possible. 43 } 44 45 // Output: 46 // context canceled 47 }