-
Notifications
You must be signed in to change notification settings - Fork 0
/
pid_file.go
68 lines (59 loc) · 1.44 KB
/
pid_file.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
package delayed_job
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/mitchellh/go-ps"
)
var pidFile *string
func init() {
if "windows" == runtime.GOOS {
pidFile = flag.String("pid_file", "delayed_job.pid", "File containing process PID")
} else {
pidFile = flag.String("pid_file", "/var/run/delayed_job.pid", "File containing process PID")
}
}
func isPidInitialize() bool {
ret := false
flag.Visit(func(f *flag.Flag) {
if "pid_file" == f.Name {
ret = true
}
})
return ret
}
func createPidFile(pidFile, image string) error {
if pidString, err := ioutil.ReadFile(pidFile); err == nil {
pid, err := strconv.Atoi(string(pidString))
if err == nil {
if pr, e := ps.FindProcess(pid); nil != e || (nil != pr &&
strings.Contains(strings.ToLower(pr.Executable()), strings.ToLower(image))) {
return fmt.Errorf("pid file found, ensure "+image+" is not running or delete %s", pidFile)
}
}
}
file, err := os.Create(pidFile)
if err != nil {
if e := os.MkdirAll(filepath.Dir(pidFile), 0666); e != nil {
log.Println("[warn] mkdir '"+filepath.Dir(pidFile)+"' fail:", e)
}
file, err = os.Create(pidFile)
if err != nil {
return err
}
}
defer file.Close()
_, err = fmt.Fprintf(file, "%d", os.Getpid())
return err
}
func removePidFile(pidFile string) {
if err := os.Remove(pidFile); err != nil {
fmt.Printf("Error removing %s: %s\r\n", pidFile, err)
}
}