/
program.go
106 lines (96 loc) · 2.37 KB
/
program.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package system
import (
"bytes"
"fmt"
"os"
"os/signal"
"path/filepath"
"runtime"
"strconv"
"syscall"
"time"
)
type exitFunc func()
// SecurityExitProcess Listen for system signals, execute exitFunc
// to release program resources, and exit gracefully.
func SecurityExitProcess(exitFunc exitFunc) {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
for s := range c {
switch s {
case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT:
{
fmt.Printf("security exit by %s signal.\n", s)
exitFunc()
time.Sleep(time.Millisecond * time.Duration(1500))
os.Exit(0)
}
default:
{
fmt.Printf("unknown exit by %s signal.\n", s)
exitFunc()
time.Sleep(time.Millisecond * time.Duration(1500))
os.Exit(0)
}
}
}
}
// SecurityExitProcessWithNotify Listen for system signals and notify, execute exitFunc
// to release program resources, and exit gracefully.
func SecurityExitProcessWithNotify(exitFunc exitFunc, cc chan string) {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
for {
select {
case s := <-c:
{
switch s {
case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT:
{
fmt.Printf("security exit by %s signal.\n", s)
exitFunc()
time.Sleep(time.Millisecond * time.Duration(1500))
os.Exit(0)
}
default:
{
fmt.Printf("unknown exit by %s signal.\n", s)
exitFunc()
time.Sleep(time.Millisecond * time.Duration(1500))
os.Exit(0)
}
}
}
case v := <-cc:
{
fmt.Printf("security exit by notify of %s.\n", v)
exitFunc()
time.Sleep(time.Millisecond * time.Duration(1500))
os.Exit(0)
}
}
}
}
// GetGoroutineID Get the coroutine ID (this method affects performance and is only used for debugging).
func GetGoroutineID() int64 {
b := make([]byte, 64)
runtime.Stack(b, false)
b = bytes.TrimPrefix(b, []byte("goroutine "))
b = b[:bytes.IndexByte(b, ' ')]
n, err := strconv.ParseInt(string(b), 10, 64)
if err != nil {
fmt.Printf("%s strconv.ParseUint error = %s\n", string(b), err)
return -1
}
return n
}
func GetPath() (string, error) {
path, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return "", err
}
return path, nil
}
func GetPID() int {
return os.Getpid()
}