-
Notifications
You must be signed in to change notification settings - Fork 500
/
pidfile.go
87 lines (71 loc) · 1.76 KB
/
pidfile.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
package common
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"build-booster/common/conf"
)
var pidFile string
// SavePid save current process's pid into files.
func SavePid(processConfig conf.ProcessConfig) error {
pidPath := filepath.Join(processConfig.PidDir, filepath.Base(os.Args[0])+".pid")
if fi, err := os.Stat(pidPath); err == nil && !fi.IsDir() {
_ = os.Remove(pidPath)
} else if !os.IsNotExist(err) {
return err
}
SetPidFilePath(pidPath)
if err := WritePid(); err != nil {
return fmt.Errorf("write pid file failed. err:%s", err.Error())
}
return nil
}
// SetPidFilePath sets the pidFile path.
func SetPidFilePath(p string) {
pidFile = p
}
// WritePid the pidFile based on the flag. It is an error if the pidFile hasn't
// been configured.
func WritePid() error {
if pidFile == "" {
return fmt.Errorf("pidFile is not set")
}
if err := os.MkdirAll(filepath.Dir(pidFile), os.FileMode(0755)); err != nil {
return err
}
file, err := AtomicFileNew(pidFile, os.FileMode(0644))
if err != nil {
return fmt.Errorf("error opening pidFile %s: %s", pidFile, err)
}
defer func() {
_ = file.Close() // in case we fail before the explicit close
}()
_, err = fmt.Fprintf(file, "%d", os.Getpid())
if err != nil {
return err
}
err = file.Close()
if err != nil {
return err
}
return nil
}
// ReadPid the pid from the configured file. It is an error if the pidFile hasn't
// been configured.
func ReadPid() (int, error) {
if pidFile == "" {
return 0, fmt.Errorf("pidFile is empty")
}
d, err := ioutil.ReadFile(pidFile)
if err != nil {
return 0, err
}
pid, err := strconv.Atoi(string(bytes.TrimSpace(d)))
if err != nil {
return 0, fmt.Errorf("error parsing pid from %s: %s", pidFile, err)
}
return pid, nil
}