-
Notifications
You must be signed in to change notification settings - Fork 8
/
single_unix.go
54 lines (44 loc) · 1.27 KB
/
single_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
// +build !windows
package single
import (
"fmt"
"os"
"syscall"
)
// Lock tries to obtain an exclude lock on a lockfile and exits the program if an error occurs
func (s *Single) Lock() error {
// open/create lock file
f, err := os.OpenFile(s.Lockfile(), os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return err
}
s.file = f
// set the lock type to F_WRLCK, therefor the file has to be opened writable
flock := syscall.Flock_t{
Type: syscall.F_WRLCK,
Pid: int32(os.Getpid()),
}
// try to obtain an exclusive lock - FcntlFlock seems to be the portable *ix way
if err := syscall.FcntlFlock(s.file.Fd(), syscall.F_SETLK, &flock); err != nil {
return ErrAlreadyRunning
}
return nil
}
// Unlock releases the lock, closes and removes the lockfile
func (s *Single) Unlock() error {
// set the lock type to F_UNLCK
flock := syscall.Flock_t{
Type: syscall.F_UNLCK,
Pid: int32(os.Getpid()),
}
if err := syscall.FcntlFlock(s.file.Fd(), syscall.F_SETLK, &flock); err != nil {
return fmt.Errorf("failed to unlock the lock file: %w", err)
}
if err := s.file.Close(); err != nil {
return fmt.Errorf("failed to close the lock file: %w", err)
}
if err := os.Remove(s.Lockfile()); err != nil {
return fmt.Errorf("failed to remove the lock file: %w", err)
}
return nil
}