forked from djcas9/envdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pid_file_posix.go
67 lines (54 loc) · 1.19 KB
/
pid_file_posix.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 daemon
import (
"fmt"
"os"
"syscall"
)
// PidFile contains information of pid-file.
type PidFile struct {
file *os.File
path string
}
// ErrWoldBlock indicates on locking pid-file by another process.
var ErrWouldBlock = syscall.EWOULDBLOCK
// func LockPidFile trys create and lock pid-file.
func LockPidFile(path string, perm os.FileMode) (pidf *PidFile, err error) {
var fileLen int
var file *os.File
file, err = os.OpenFile(path, os.O_WRONLY|os.O_CREATE, perm)
if err != nil {
return
}
if err = syscall.Flock(int(file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
if err == syscall.EWOULDBLOCK {
// allready locked by other process instance
file.Close()
return
}
goto SKIP
}
if fileLen, err = fmt.Fprint(file, os.Getpid()); err != nil {
goto SKIP
}
if err = file.Truncate(int64(fileLen)); err != nil {
goto SKIP
}
SKIP:
if err != nil {
syscall.Unlink(path)
file.Close()
} else {
pidf = &PidFile{file, path}
}
return
}
// func Unlock unlocks and removes pid-file.
func (pidf *PidFile) Unlock() (err error) {
err = syscall.Unlink(pidf.path)
err2 := pidf.file.Close()
// return one of two errors
if err == nil {
err = err2
}
return
}