-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpid.go
67 lines (56 loc) · 1.34 KB
/
pid.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
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
)
// PIDFile stores (few) informations about a PID file
type PIDFile struct {
Path string
}
func checkPIDFileExists(path string) error {
if pidByte, err := ioutil.ReadFile(path); err == nil {
pidString := strings.TrimSpace(string(pidByte))
if pid, err := strconv.Atoi(pidString); err == nil {
if pidIsRunning(pid) {
return fmt.Errorf("pid file '%s' already exists", path)
}
}
}
return nil
}
// NewPIDFile create a PIDFile if there no other instance already running
func NewPIDFile(path string) (*PIDFile, error) {
if err := checkPIDFileExists(path); err != nil {
return nil, err
}
if err := os.MkdirAll(filepath.Dir(path), os.FileMode(0755)); 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
}
// Remove deletes the PIDFile
func (file PIDFile) Remove() error {
return os.Remove(file.Path)
}
func pidIsRunning(pid int) bool {
process, err := os.FindProcess(pid)
if err != nil {
return false
}
err = process.Signal(syscall.Signal(0))
if err != nil && err.Error() == "no such process" {
return false
}
if err != nil && err.Error() == "os: process already finished" {
return false
}
return true
}