-
Notifications
You must be signed in to change notification settings - Fork 2
/
pidfile.go
82 lines (67 loc) · 1.59 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
package pidfile
import (
"errors"
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
"syscall"
)
var (
ErrProcessRunning = errors.New("process is running")
ErrFileStale = errors.New("pidfile exists but process is not running")
ErrFileInvalid = errors.New("pidfile has invalid contents")
)
// Remove a pidfile
func Remove(filename string) error {
return os.RemoveAll(filename)
}
// Write writes a pidfile, returning an error
// if the process is already running or pidfile is orphaned
func Write(filename string) error {
return WriteControl(filename, os.Getpid(), false)
}
func WriteControl(filename string, pid int, overwrite bool) error {
// Check for existing pid
oldpid, err := pidfileContents(filename)
if err != nil && !os.IsNotExist(err) {
return err
}
// We have a pid
if err == nil {
if pidIsRunning(oldpid) {
return ErrProcessRunning
}
if !overwrite {
return ErrFileStale
}
}
// We're clear to (over)write the file
return ioutil.WriteFile(filename, []byte(fmt.Sprintf("%d\n", pid)), 0644)
}
func pidfileContents(filename string) (int, error) {
contents, err := ioutil.ReadFile(filename)
if err != nil {
return 0, err
}
pid, err := strconv.Atoi(strings.TrimSpace(string(contents)))
if err != nil {
return 0, ErrFileInvalid
}
return pid, nil
}
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
}