-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
42 lines (38 loc) · 1007 Bytes
/
main.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
42
package signals
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
// Go offers first hand support for handling UNIX signals.
// We may want our programs to gracefully handle signals
// such as SIGTERM etc, here is how that can be done.
func Run() {
handleSignal()
}
// Go handles signals by using a buffered channel
func handleSignal() {
signals := make(chan os.Signal, 1)
// Notify on sigterm and keyboard interrupt.
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
shouldExit := make(chan bool, 1)
go func() {
// Read from the signals channel if something appears.
for {
select {
case sig := <-signals:
fmt.Println(sig)
shouldExit <- true
case <-time.After(5 * time.Second):
// Stop hanging indefinitely if user doesn't input an appropriate signal.
fmt.Println("Timeout passed, exiting because no signal was sent!")
shouldExit <- true
}
}
}()
// Block until the signal has been received.
<-shouldExit
fmt.Println("Gracefully exiting...")
}