-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpidfile.go
More file actions
88 lines (73 loc) · 1.6 KB
/
pidfile.go
File metadata and controls
88 lines (73 loc) · 1.6 KB
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
package pidfile
import (
"fmt"
"io/ioutil"
"os"
"syscall"
"path/filepath"
"strconv"
)
type PidFile struct {
path string
}
func getPidProcess(path string) (*os.Process, error) {
pidString, err := ioutil.ReadFile(path);
if err != nil {
return nil, err
}
pid, err := strconv.Atoi(string(pidString))
if err != nil {
return nil, fmt.Errorf("%s fake", path)
}
proc, err := os.FindProcess(pid)
if err != nil {
return nil, err
}
return proc, nil
}
func checkPidFileAlreadyExists(path string) error {
if pidString, err := ioutil.ReadFile(path); err == nil {
if pid, err := strconv.Atoi(string(pidString)); err == nil {
if _, err := os.Stat(filepath.Join("/proc", string(pid))); err == nil {
return fmt.Errorf("pid process is running")
}
}
}
return nil
}
func (file *PidFile) remove() error {
if err := os.Remove(file.path); err != nil {
return err
}
return nil
}
func New(path string) (*PidFile, error) {
if err := checkPidFileAlreadyExists(path); err != nil {
return nil, err
}
if err := ioutil.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil {
return nil, err
}
return &PidFile{path: path}, nil
}
func Load(path string) (*PidFile, error) {
if _, err := os.Stat(path); err != nil {
return nil, err
}
return &PidFile{path: path}, nil
}
func (file *PidFile) Kill() error {
defer file.remove()
proc, err := getPidProcess(file.path)
if err != nil {
return err
}
return proc.Kill()
}
func (file *PidFile) HUP() error {
proc, err := getPidProcess(file.path)
if err != nil {
return err
}
return proc.Signal(os.Signal(syscall.SIGHUP))
}