-
Notifications
You must be signed in to change notification settings - Fork 0
/
pid.go
69 lines (54 loc) · 1.18 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
68
69
package tinyfile
import (
"errors"
"fmt"
"os"
)
var (
ErrAnotherProcessRunning = errors.New("pid file is aleady exist")
ErrAleadySetPid = errors.New("aleady seted pid on this process")
PidFileFlg = os.O_CREATE | os.O_WRONLY
PidFilePermission os.FileMode = 0664
)
var pidFilepath string = ""
// PidSet create pid file.
//
// require run PidClean() on process end.
// this function work only once.
func PidSet(path string) error {
if pidFilepath != "" {
return ErrAleadySetPid
}
if FileExist(path) {
return ErrAnotherProcessRunning
}
pid := os.Getpid()
f, err := os.OpenFile(path, PidFileFlg, PidFilePermission)
if err != nil {
return err
}
defer f.Close()
fmt.Fprintf(f, "%d", pid)
pidFilepath = path
return nil
}
// PidClean delete pid file of created by PidSet()
func PidClean() error {
if pidFilepath != "" {
err := os.Remove(pidFilepath)
if err == nil {
pidFilepath = ""
}
return err
}
return nil
}
// FileExist check path is file and exist
// true is only file exist and type is file
func FileExist(path string) bool {
f, err := os.Stat(path)
if errors.Is(err, os.ErrNotExist) {
return false
}
return !f.IsDir()
}