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 aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris 6 // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris 7 8 package signal_test 9 10 import ( 11 "context" 12 "fmt" 13 "log" 14 "os" 15 "os/signal" 16 "time" 17 ) 18 19 // This example passes a context with a signal to tell a blocking function that 20 // it should abandon its work after a signal is received. 21 func ExampleNotifyContext() { 22 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) 23 defer stop() 24 25 p, err := os.FindProcess(os.Getpid()) 26 if err != nil { 27 log.Fatal(err) 28 } 29 30 // On a Unix-like system, pressing Ctrl+C on a keyboard sends a 31 // SIGINT signal to the process of the program in execution. 32 // 33 // This example simulates that by sending a SIGINT signal to itself. 34 if err := p.Signal(os.Interrupt); err != nil { 35 log.Fatal(err) 36 } 37 38 select { 39 case <-time.After(time.Second): 40 fmt.Println("missed signal") 41 case <-ctx.Done(): 42 fmt.Println(ctx.Err()) // prints "context canceled" 43 stop() // stop receiving signal notifications as soon as possible. 44 } 45 46 // Output: 47 // context canceled 48 } 49