-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.go
38 lines (33 loc) · 900 Bytes
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package cli
import (
"context"
"os"
"os/signal"
"syscall"
)
// sig is a side channel that may receive signals when ReceiveSignal. Any
// context that was created via cli.Context will wait for signals on this
// channel.
var sig = make(chan os.Signal)
// Context returns a context that is cancelled automatically when a SIGINT,
// SIGQUIT or SIGTERM signal is received.
func Context() context.Context {
ctx, cancel := context.WithCancel(context.Background())
signal.Notify(sig, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
go func() {
select {
case <-sig:
cancel()
}
}()
return ctx
}
// ReceiveSignal propagates the given signal to all contexts that may have been
// created via cli.Context(). This function is only useful when the terminal is
// hijacked and you want to emulate signals manually.
func ReceiveSignal(s os.Signal) {
select {
case sig <- s:
default:
}
}