forked from remind101/empire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flock.go
47 lines (40 loc) · 957 Bytes
/
flock.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
package flock
import (
"os"
"syscall"
)
// Lock is an implementation of the sync.Locker interface that is backed by a
// file flock(2).
type Lock struct {
f *os.File
fd uintptr
}
// New returns a new Lock instance using the provided file as the backend.
func New(f *os.File) *Lock {
return &Lock{
f: f,
fd: f.Fd(),
}
}
// NewPath first creates the file at the given path, then returns a new Lock
// instance backed by the file.
func NewPath(path string) (*Lock, error) {
f, err := os.Create(path)
if err != nil {
return nil, err
}
return New(f), nil
}
// Lock aquires a lock on the file using flock(2). Lock will block if the file
// was previously locked.
func (l *Lock) Lock() {
if err := syscall.Flock(int(l.fd), syscall.LOCK_EX); err != nil {
panic(err)
}
}
// Unlock removes the lock on the file using flock(2).
func (l *Lock) Unlock() {
if err := syscall.Flock(int(l.fd), syscall.LOCK_UN); err != nil {
panic(err)
}
}