-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
sync_unix.go
57 lines (46 loc) · 978 Bytes
/
sync_unix.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
//go:build !windows
// +build !windows
package utils
import (
"io"
"syscall"
"github.com/Laisky/errors/v2"
)
// FLock lock by file
type FLock interface {
Lock() error
Unlock() error
}
type flock struct {
fpath string
fd int
}
// NewFlock new file lock
func NewFlock(lockFilePath string) FLock {
return &flock{
fpath: lockFilePath,
}
}
func (f *flock) Unlock() error {
if err := syscall.Close(f.fd); err != nil {
return errors.Wrap(err, "close file")
}
_ = syscall.Unlink(f.fpath)
return nil
}
func (f *flock) Lock() (err error) {
f.fd, err = syscall.Open(f.fpath, syscall.O_CREAT|syscall.O_RDWR|syscall.O_CLOEXEC, 0666)
if err != nil {
return errors.Wrapf(err, "open `%s`", f.fpath)
}
flock := syscall.Flock_t{
Type: syscall.F_WRLCK,
Whence: io.SeekStart,
Start: 0,
Len: 0,
}
if err := syscall.FcntlFlock(uintptr(f.fd), syscall.F_SETLK, &flock); err != nil {
return errors.Wrap(err, "FcntlFlock(F_SETLK)")
}
return nil
}