-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsigint.go
54 lines (45 loc) · 1.18 KB
/
sigint.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
51
52
53
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
const FILE_NAME = "go-example.txt"
func main() {
// Setup our Ctrl+C handler
SetupCloseHandler()
// Run our program... We create a file to clean up then sleep
CreateFile()
for {
fmt.Println("- Sleeping")
time.Sleep(10 * time.Second)
}
}
// SetupCloseHandler creates a 'listener' on a new goroutine which will notify the
// program if it receives an interrupt from the OS. We then handle this by calling
// our clean up procedure and exiting the program.
func SetupCloseHandler() {
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
fmt.Println("\r- Ctrl+C pressed in Terminal")
DeleteFiles()
os.Exit(0)
}()
}
// Used to simulate a 'clean up' function to run on shutdown. Because it's
// just an example it doesn't have any error handling.
func DeleteFiles() {
fmt.Println("- Run Clean Up - Delete Our Example File")
_ = os.Remove(FILE_NAME)
fmt.Println("- Good bye!")
}
// Create a file so we have something to clean up when we close our program.
func CreateFile() {
fmt.Println("- Create Our Example File")
file, _ := os.Create(FILE_NAME)
defer file.Close()
}