-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess.go
More file actions
64 lines (54 loc) · 1.32 KB
/
Copy pathprocess.go
File metadata and controls
64 lines (54 loc) · 1.32 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
package process
import (
"bufio"
"errors"
"fmt"
"os"
"syscall"
)
func IsRunning(pidFilePath string) (bool, error) { // 0: not running, 1: running
if pidFilePath == "" {
return false, errors.New("process.checkProcessIsRunning(): invalid parmas (may be zero-values)")
}
if _, err := os.Stat(pidFilePath); err == nil {
// pid file exist
file, err := os.Open(pidFilePath)
if err != nil {
return false, err
}
var pid int
fmt.Fscanf(file, "%d", &pid)
file.Close()
if process, err := os.FindProcess(pid); err == nil {
if err := process.Signal(syscall.Signal(0)); err == nil {
// process is running
return true, nil
} else {
// process is stopped
f, err := os.OpenFile(pidFilePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
if err != nil {
return false, err
}
defer f.Close()
pid = os.Getpid()
w := bufio.NewWriter(f)
fmt.Fprintf(w, "%d", pid)
w.Flush()
return false, nil
}
}
} else if os.IsNotExist(err) {
// pid file not exist
file, err := os.OpenFile(pidFilePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
if err != nil {
return false, err
}
defer file.Close()
pid := os.Getpid()
w := bufio.NewWriter(file)
fmt.Fprintf(w, "%d", pid)
w.Flush()
return false, nil
}
return false, fmt.Errorf("process.IsRunning(): Unexpected Error")
}