forked from akash-network/node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
signal.go
41 lines (33 loc) · 780 Bytes
/
signal.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
39
40
41
package common
import (
"context"
"os"
"os/signal"
"syscall"
)
func WatchSignals(ctx context.Context, cancel context.CancelFunc) <-chan struct{} {
donech := make(chan struct{})
sigch := make(chan os.Signal, 1)
signal.Notify(sigch, syscall.SIGINT, syscall.SIGHUP, syscall.SIGTERM)
go func() {
defer close(donech)
defer signal.Stop(sigch)
select {
case <-ctx.Done():
case <-sigch:
cancel()
}
}()
return donech
}
func RunForever(fn func(ctx context.Context) error) error {
return RunForeverWithContext(context.Background(), fn)
}
func RunForeverWithContext(ctx context.Context, fn func(ctx context.Context) error) error {
ctx, cancel := context.WithCancel(ctx)
donech := WatchSignals(ctx, cancel)
err := fn(ctx)
cancel()
<-donech
return err
}