-
Notifications
You must be signed in to change notification settings - Fork 17.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
os/signal: add NotifyContext to cancel context using system signals
Fixes #37255 Change-Id: Ic0fde3498afefed6e4447f8476e4da7c1faa7145 Reviewed-on: https://go-review.googlesource.com/c/go/+/219640 Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Go Bot <[email protected]> Trust: Giovanni Bajo <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]>
- Loading branch information
1 parent
8248b57
commit b6dbaef
Showing
3 changed files
with
284 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
// Copyright 2020 The Go Authors. All rights reserved. | ||
// Use of this source code is governed by a BSD-style | ||
// license that can be found in the LICENSE file. | ||
|
||
// +build aix darwin dragonfly freebsd linux netbsd openbsd solaris | ||
|
||
package signal_test | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"log" | ||
"os" | ||
"os/signal" | ||
"time" | ||
) | ||
|
||
// This example passes a context with a signal to tell a blocking function that | ||
// it should abandon its work after a signal is received. | ||
func ExampleNotifyContext() { | ||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) | ||
defer stop() | ||
|
||
p, err := os.FindProcess(os.Getpid()) | ||
if err != nil { | ||
log.Fatal(err) | ||
} | ||
|
||
// On a Unix-like system, pressing Ctrl+C on a keyboard sends a | ||
// SIGINT signal to the process of the program in execution. | ||
// | ||
// This example simulates that by sending a SIGINT signal to itself. | ||
if err := p.Signal(os.Interrupt); err != nil { | ||
log.Fatal(err) | ||
} | ||
|
||
select { | ||
case <-time.After(time.Second): | ||
fmt.Println("missed signal") | ||
case <-ctx.Done(): | ||
fmt.Println(ctx.Err()) // prints "context canceled" | ||
stop() // stop receiving signal notifications as soon as possible. | ||
} | ||
|
||
// Output: | ||
// context canceled | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters