-
Notifications
You must be signed in to change notification settings - Fork 0
/
unix-signals.go
50 lines (41 loc) · 1.59 KB
/
unix-signals.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
43
44
45
46
47
48
49
50
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
)
/*
Sometimes we’d like our Go programs to intelligently handle Unix signals.
For example, we might want a server to gracefully shutdown when it receives a SIGTERM,
or a command-line tool to stop processing input if it receives a SIGINT.
When we run this program it will block waiting for a signal.
By typing ctrl-C (which the terminal shows as ^C) we can send a SIGINT signal,
causing the program to print interrupt and then exit.
*/
func main() {
fmt.Println("Sample started")
defer fmt.Println("Sample terminated")
// Go signal notification works by sending os.Signal values on a channel.
// We’ll create a channel to receive these notifications (we’ll also make one to notify
// us when the program can exit).
osSignalChannel := make(chan os.Signal, 1)
doneChannel := make(chan bool, 1)
// signal.Notify registers the given channel to receive notifications of the specified signals.
signal.Notify(osSignalChannel, syscall.SIGINT, syscall.SIGTERM)
// This goroutine executes a blocking receive for signals. When it gets one it’ll print
// it out and then notify the program that it can finish.
go func() {
fmt.Println("Goroutine waiting for OS signals...")
sig := <-osSignalChannel
fmt.Println()
fmt.Println(sig)
doneChannel <- true
fmt.Println("Goroutine terminated")
}()
// The program will wait here until it gets the expected signal (as indicated by the goroutine
// above sending a value on done) and then exit.
fmt.Println("Main waiting for bool signal...")
<-doneChannel
fmt.Println("Main terminated")
}